val start = 1
val end = 10
for (i <- start to end) {
println(i)
}
for (i <- 1 until 3) {
println(i)
}
for (i <- 1 to 10 if i % 2 == 0) {
println(i)
}
for (i <- 1 to 10; j = i * 10) {
println(j)
}
for (i <- 1 to 9; j <- 1 to 9) {
println(i * j)
}
val res = for(i <- 1 to 10) yield {
if (i % 2 == 0) "even"
else "odd"
}
// 使用花括号{}代替小括号()
for {
i <- 1 to 3
j <- 1 to 3
} {
println(i * j)
}
// 控制步长
for (i <- Range(1, 10, 2))
println(i)
与 If 语句不同,While 语句本身没有值,即整个 While 语句的结果是 Unit 类型的()
Scala 内置控制结构特地去掉了 break 和 continue,是为了更好的适应函数化编程
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* A block from which one can exit with a `break`. The `break` may be
* executed further down in the call stack provided that it is called on the
* exact same instance of `Breaks`.
*/
def breakable(op: => Unit) {
try {
op
} catch {
case ex: BreakControl =>
if (ex ne breakException) throw ex
}
}
1
2
3
4
5
6
7
import scala.util.control.Breaks._
breakable {
for (i <- 1 to 10) {
println(i)
if (i > 4) break // break out of the for loop
}
}