其他一些迭代方法:
scala> xs.foreach (println)
first
second
third
foreach以及类似的map,它将返回一些内容(该函数的结果,对于println来说,是Unit,因此是Units的列表)
scala> val lens = for (x <- xs) yield (x.length)
lens: Array[Int] = Array(5, 6, 5)
使用元素,而不是索引
scala> ("" /: xs) (_ + _)
res21: java.lang.String = firstsecondthird
可折
for(int i=0, j=0; i+j<100; i+=j*2, j+=i+2) {...}
可以通过递归来完成:
def ijIter (i: Int = 0, j: Int = 0, carry: Int = 0) : Int =
if (i + j >= 100) carry else
ijIter (i+2*j, j+i+2, carry / 3 + 2 * i - 4 * j + 10)
进位部分只是一个示例,可以对i和j进行操作。不必是Int。
对于更简单的东西,更接近通常的for循环:
scala> (1 until 4)
res43: scala.collection.immutable.Range with scala.collection.immutable.Range.ByOne = Range(1, 2, 3)
scala> (0 to 8 by 2)
res44: scala.collection.immutable.Range = Range(0, 2, 4, 6, 8)
scala> (26 to 13 by -3)
res45: scala.collection.immutable.Range = Range(26, 23, 20, 17, 14)
或不订购:
List (1, 3, 2, 5, 9, 7).foreach (print)