开发者

Scala for-comprehension syntax

开发者 https://www.devze.com 2023-02-09 11:48 出处:网络
In the following code, inside the for comprehension, I can refer to the string and index using a tuple dereference:

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"开发者_如何学Go, "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.


strings.zipWithIndex.foreach{case(x,y) => println(x,y)}

res:

(a,0)
(b,1)
(c,2)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号