Question

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)
Was it helpful?

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)

OTHER TIPS

A for comprehension is not like a for loop in that the terms are evaluated for each previous term. As an example, look at the results below. I don't think that's what you are looking for:

    scala> val elements = List("a", "b", "c", "d")
elements: List[java.lang.String] = List(a, b, c, d)

scala> for (e <- elements; i <- 0 until elements.length) yield (e, i)
res2: List[(java.lang.String, Int)] = List((a,0), (a,1), (a,2), (a,3), (b,0), (b,1), (b,2), (b,3), (c,0), (c,1), (c,2), (c,3), (d,0), (d,1), (d,2), (d,3))

tenshi's answer is probably more on track with your desired result, but I hope this counterexample is useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top