因为 Scala 没有带索引的旧 Java 风格 for
循环,
// does not work
val xs = Array("first", "second", "third")
for (i=0; i<xs.length; i++) {
println("String #" + i + " is " + xs(i))
}
我们如何能够有效地迭代,而不使用 var
?
你可以的
val xs = Array("first", "second", "third")
val indexed = xs zipWithIndex
for (x <- indexed) println("String #" + x._2 + " is " + x._1)
但是这个列表被遍历了两次,效率不是很高。