在下面的代码中,在 for
里面理解,我可以使用元组取消引用来引用字符串和索引:
val strings = List("a", "b", "c")
for (stringWithIndex <- strings.zipWithIndex) {
// Do something with stringWithIndex._1 (string) and stringWithIndex._2 (index)
}
Scala 语法中是否有任何方法可以使用
stringWithIndex
拆分为部分(字符串和索引)内for
领悟标题 ,这样代码的读者就不必对 stringWithIndex._1
的值感到疑惑。和 stringWithIndex._2
?我尝试了以下操作,但无法编译:
for (case (string, index) <- strings.zipWithIndex) {
// Do something with string and index
}
最佳答案
你几乎明白了:
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
看,不需要
case
关键词。
关于Scala for-comprehension 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4933697/