基础使用方式
最基础的是范围遍历,to包含上确界,until不包含上确界,给出代码实例:
package example
object MyExample {
def main(args: Array[String]): Unit = {
for (i <- 0 to 3) { // 会输出3
println(i)
}
println("===========")
for (i <- 0 until 3) { // 不会输出3
println(i)
}
}
}
循环的元素也可以直接遍历:
package example
object MyExample {
def main(args: Array[String]): Unit = {
val nums = Seq(1, 2, 3)
for (n <- nums) {
println(n)
}
val strs = Seq("1", "Two", "3.0")
for (s <- strs) {
println(s)
}
}
}
循环守卫
如果我们想在循环时增加过滤条件,可以使用如下方式:
package example
object MyExample {
def myFilter(n: Int): Boolean = {
n % 2 != 0
}
def main(args: Array[String]): Unit = {
val nums = Seq(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
for (i <- nums if i % 2 == 0) {
println(i) // 只打印偶数
}
println("=======")
for (i <- nums if myFilter(i)) {
println(i) // 只打印奇数
}
}
}
高维循环
直接给出代码实例
package example
object MyExample {
def main(args: Array[String]): Unit = {
for (i <- 1 to 3; j <- 1 to i) {
println(s"($i, $j)")
}
println("================")
for (i <- 1 to 4;
j <- 1 to i if j % 2 == 0) {
println(s"($i, $j)") // 只输出第二位是偶数的
}
}
}