在Scala中,for循环通常用于遍历集合或生成序列。以下是一些常见的for循环用法:
1. 遍历集合:
val list = List(1, 2, 3, 4, 5)
for (item <- list) {
println(item)
}
2. 遍历范围:
for (i <- 1 to 5) {
println(i)
}
3. 遍历带步长的范围:
for (i <- 1 until 10 by 2) {
println(i)
}
4. 遍历数组:
val arr = Array(1, 2, 3, 4, 5)
for (item <- arr) {
println(item)
}
5. 遍历带有索引的集合:
val list = List("a", "b", "c")
for ((index, item) <- list.zipWithIndex) {
println(s"Element at index $index is $item")
}
6. 使用if过滤条件:
val list = List(1, 2, 3, 4, 5)
for (item <- list if item % 2 == 0) {
println(item)
}