Reputation: 1803
Scala newbie question. I want to map a list to another list but I want to every object to know its sequence number. In the following simple code, what is the right alternative to the usage of var v?
class T (s: String, val sequence:Int)
val stringList = List("a","b","C")
var v = 0
val tList = stringList.map(s => { v=v+1; new T(s, v);})
Upvotes: 0
Views: 151
Reputation: 1368
You can use zipWithIndex
to get a tuple for each element containing the actual element and the index, then just map that tuple to your object:
List("a", "b", "C")
.zipWithIndex
.map(e => new T(e._1, e._2))
Upvotes: 1
Reputation: 51271
val tList = List.tabulate(stringList.length)(idx => new T(stringList(idx), idx))
Upvotes: 1