scala> for (i <- 1 to 5) println(i)
1
2
3
4
5
用yeild/for组合
scala> val evens = for ( i <- 1 to 5) yield i * 2
evens: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10)
scala> val a = Array("Apple", "banana")
scala> for( i <- 0 until a.length){ println(s"$i is ${a(i)}") }
0 is Apple
1 is banana
zipWithIndex:
scala> for((e, count) <- a.zipWithIndex) {
| println(s"$count is $e")
| }
0 is Apple
1 is banana
scala> a.foreach(println)
Apple
banana
scala> a.foreach(e => println(e.toUpperCase))
APPLE
BANANA
多行实现的:
scala> a.foreach{ e =>
| val s = e.toUpperCase
def toUpperCase(): String def toUpperCase(x$1: java.util.Locale): String
| val s = e.toUpperCase
| println(s)
| }
APPLE
BANANA
如果遇到了多维数组的情况
scala> for (i <- 1 to 2 ; j <- 1 to 2) println(s"i = $i, j = $j")
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
也可以:
scala> for{
| i <- 1 to 2
| j <- 1 to 2
| } println(s"i = $i, j = $j")
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2