to
for (i <- 1 to 3) {
println(i)
}
//相当于
val range=(1 to 3) //range: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3)
range.foreach(println)
until
for (i <- 1 until 3) {
println("i: " + i)
}
//i: 1
//i: 2
多范围
for( i <- 1 to 3; j <- 1 to 3){
//...
}
//相当于
for( i <- 1 to 3){
for( j <- 1 to 3){
//...
}
}
List
val list=List(1,2,3) // list: List[Int] = List(1, 2, 3)
for (elem <- list) {
println(elem)
}
// 1
// 2
// 3
条件
val list = List(1, 2, 3, 4, 5, 6);
for (i <- list if i != 3; if i < 5) {
println("i: " + i);
}
//相当于
for (i <- list) {
if (i != 3 && i < 5) {
println("i: " + i);
}
}
// i: 1
// i: 2
// i: 4
yield
返回for循环中符合条件的变量值并组成被遍历的类型
val list = List(1,2,3,4,5,6) // list: List[Int] = List(1, 2, 3, 4, 5, 6)
var retVal = for{ i <- list
if i != 3; if i < 5
} yield i // retVal: List[Int] = List(1, 2, 4)
for( i <- retVal){
println( "i: " + i );
}
// i: 1
// i: 2
// i: 4