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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With