Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala for-comprehension syntax

In the following code, inside the for comprehension, I can refer to the string and index using a tuple dereference:

val strings = List("a", "b", "c")
for (stringWithIndex <- strings.zipWithIndex) {
  // Do something with stringWithIndex._1 (string) and stringWithIndex._2 (index)
}

Is there any way in the Scala syntax to have the stringWithIndex split into the parts (string and index) within the for comprehension header, so that readers of the code do not have to wonder at the values of stringWithIndex._1 and stringWithIndex._2?

I tried the following, but it would not compile:

for (case (string, index) <- strings.zipWithIndex) {
  // Do something with string and index
}
like image 527
Ralph Avatar asked Feb 08 '11 13:02

Ralph


1 Answers

You almost got it:

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

scala> for ( (string, index) <- strings.zipWithIndex)
       | { println("str: "+string + " idx: "+index) }
str: a idx: 0
str: b idx: 1
str: c idx: 2

See, no need for case keyword.

like image 115
pedrofurla Avatar answered Sep 28 '22 00:09

pedrofurla