Scala for-comprehension语法

时间:2011-02-08 13:36:39

标签: scala tuples for-comprehension

在下面的代码中,在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._1stringWithIndex._2的值?

我尝试了以下内容,但无法编译:

for (case (string, index) <- strings.zipWithIndex) {
  // Do something with string and index
}

2 个答案:

答案 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)