scala - How can I change mutable incremental number to be functional -
i have code uniquekeygenerator, there mutable variable number incrementally added, because want create generated value predictable, wonder how can alter value instead of variable
object uniquekeygenerator { var number = 0 def generate(suiteclass: class[_]): string = { number = number + 1 suiteclass.getcanonicalname + "." + this.number } }
many in advance
if you're trying express val
instead of var
, utilize iterator
.
object uniquekeygenerator { val numbers = iterator.iterate(0)(_ + 1) def generate(suiteclass: class[_]): string = s"${suiteclass.getcanonicalname}.${numbers.next()}" }
otherwise, i'm not sure you're asking - maybe provide more context?
if have of inputs front, can write 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)
scala
No comments:
Post a Comment