Saar
Saar

Reputation: 1803

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

Upvotes: 0

Views: 151

Answers (2)

alextsc
alextsc

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

jwvh
jwvh

Reputation: 51271

val tList = List.tabulate(stringList.length)(idx => new T(stringList(idx), idx))

Upvotes: 1

Related Questions