Search code examples
scalafor-comprehension

How to use an autoincrement index in for comprehension in Scala


Is it possible to use an autoincrement counter in for comprehensions in Scala?

something like

for (element <- elements; val counter = counter+1) yield NewElement(element, counter)

Solution

  • I believe, that you are looking for zipWithIndex method available on List and other collections. Here is small example of it's usage:

    scala> val list = List("a", "b", "c")
    list: List[java.lang.String] = List(a, b, c)
    
    scala> list.zipWithIndex
    res0: List[(java.lang.String, Int)] = List((a,0), (b,1), (c,2))
    
    scala> list.zipWithIndex.map{case (elem, idx) => elem + " with index " + idx}
    res1: List[java.lang.String] = List(a with index 0, b with index 1, c with index 2)
    
    scala> for ((elem, idx) <- list.zipWithIndex) yield elem + " with index " + idx
    res2: List[java.lang.String] = List(a with index 0, b with index 1, c with index 2)