How can I change the mutable incremental number to be functional

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

object UniqueKeyGenerator {

  var number = 0

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

      

Thank you very much in advance

+3


source to share


2 answers


If you're just trying to express this with val

instead var

, you can use 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 are asking - maybe there is some other context?



If you have all the inputs from the front, 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)

      

+3


source


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

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

      



"id" is still a variable here, 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()
}

      

+1


source







All Articles