在下面的代码中,在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
}
答案 0 :(得分:21)
你几乎得到了它:
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
关键字。
答案 1 :(得分:7)
strings.zipWithIndex.foreach{case(x,y) => println(x,y)}
res:
(a,0)
(b,1)
(c,2)