一、基础循环语法
区间迭代
- 左闭右闭区间(
..
):for (i in 1..5) { print(i) } // 输出:1 2 3 4 5 :ml-citation{ref="1,7" data="citationList"}
- 左闭右开区间(
until
):for (i in 1 until 5) { print(i) } // 输出:1 2 3 4 :ml-citation{ref="2,7" data="citationList"}
- 左闭右闭区间(
倒序迭代
- 使用
downTo
关键字实现降序循环:for (i in 5 downTo 1) { print(i) } // 输出:5 4 3 2 1 :ml-citation{ref="2,7" data="citationList"}
- 使用
二、进阶循环控制
步长设置
- 通过
step
指定跳跃步长(支持正负值):for (i in 1..10 step 2) { print(i) } // 输出:1 3 5 7 9
- 通过
多变量循环
- 使用
zip()
同步遍历两个集合:val listA = listOf("A", "B", "C")
val listB = listOf(1, 2, 3) for ((a, b) in listA.zip(listB)) { println("$a-$b") }
// 输出 A-1, B-2, C-3 :
- 使用
三、数组与集合遍历
索引遍历
- 通过
indices
获取索引范围:val array = arrayOf("apple", "banana", "orange")
for (i in array.indices) { println(array[i]) } // 输出元素 :
- 通过
带索引的遍历
使用withIndex()
同时获取索引和值:for ((index, value) in array.withIndex()) { println("Index: $index, Value: $value") } // 输出索引与元素组合 :ml-
四、流程控制语句
提前退出循环
- 使用
break
终止循环:for (i in 1..10) { if (i == 5) break // 循环在 i=5 时终止 print(i) // 输出:1 2 3 4 :ml-citation{ref="4,7" data="citationList"} }
- 使用
返回值场景
- 在 Lambda 表达式(如
forEach
)中通过标签返回外层函数:fun findTarget(): Int { listOf(1,2,3).forEach { if (it == 2) return@findTarget it // 返回 2 } return -1 } :ml-citation{ref="5" data="citationList"}
- 在 Lambda 表达式(如
操作对比表
场景 | 推荐语法 | 适用场景 |
---|---|---|
范围遍历 | for (i in 1..5) |
简单连续区间迭代 |
倒序迭代 | downTo + step |
逆向或间隔跳跃遍历 |
多集合同步遍历 | zip() |
关联多个集合数据 |
带索引遍历 | withIndex() |
需同时操作索引和元素 |
通过上述方法可覆盖 90% 的 Kotlin for
循环需求,需注意避免在 Lambda 表达式中直接使用非局部返回(如 return
未加标签会直接退出外层函数。