3

I have this code UniqueKeyGenerator, there is a mutable variable number to be incrementally added, because I want to make the generated value to be predictable, I wonder how can I change it to be value instead of variable

object UniqueKeyGenerator { var number = 0 def generate(suiteClass: Class[_]): String = { number = number + 1 suiteClass.getCanonicalName + "." + this.number } } 

Many thanks in advance

2 Answers 2

3

If you're just trying to express this with a val instead of a var, you could use an Iterator.

object UniqueKeyGenerator { val numbers = Iterator.iterate(0)(_ + 1) def generate(suiteClass: Class[_]): String = s"${suiteClass.getCanonicalName}.${numbers.next()}" } 

Otherwise, I'm not sure what you're asking - maybe provide some more context?

If you have all of the inputs up front, then you can write something like this:

Seq(classOf[String], classOf[Int], classOf[String]).zipWithIndex .map({ case (suiteClass, i) => s"${suiteClass.getCanonicalName}.$i" }) // res: List(java.lang.String.0, int.1, java.lang.String.2) 
Sign up to request clarification or add additional context in comments.

Comments

1

Aside from an Iterator you can also use a closure, for example if the id you want to generate is not just the next natural number, but a result of a more complex expression.

val nextId = { var id = 0 () => { id = id + 1 // change it to something more complex if you like id } } 

The "id" here is still a variable, but it is not accessible from the outside. The only way you can use it is by calling nextId:

def generate(suiteClass: Class[_]): String = { suiteClass.getCanonicalName + "." + nextId() } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.