Saar Saar - 1 month ago 5x
Scala Question

Scala - Getting sequence id of elements during map

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 = => { v=v+1; new T(s, v);})


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")
  .map(e => new T(e._1, e._2))