Kotlin for 循环核心用法与进阶操作(2025 版)

一、‌基础循环语法
  1. 区间迭代

    • 左闭右闭区间‌(..):

      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"}

  2. 倒序迭代

    • 使用 downTo 关键字实现降序循环:

      for (i in 5 downTo 1) { print(i) } // 输出:5 4 3 2 1 ‌:ml-citation{ref="2,7" data="citationList"}


二、‌进阶循环控制
  1. 步长设置

    • 通过 step 指定跳跃步长(支持正负值):

      for (i in 1..10 step 2) { print(i) } // 输出:1 3 5 7 9 ‌

  2. 多变量循环

    • 使用 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 ‌:


三、‌数组与集合遍历
  1. 索引遍历

    • 通过 indices 获取索引范围:

      val array = arrayOf("apple", "banana", "orange")

    • for (i in array.indices) { println(array[i]) } // 输出元素 ‌:

  2. 带索引的遍历

    使用 withIndex() 同时获取索引和值:  for ((index, value) in array.withIndex()) { println("Index: $index, Value: $value") } // 输出索引与元素组合 ‌:ml-

四、‌流程控制语句
  1. 提前退出循环

    • 使用 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"} }

  2. 返回值场景

    • 在 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"}


操作对比表

场景推荐语法适用场景
范围遍历for (i in 1..5)简单连续区间迭代
倒序迭代downTo + step逆向或间隔跳跃遍历
多集合同步遍历zip()关联多个集合数据
带索引遍历withIndex()需同时操作索引和元素

通过上述方法可覆盖 90% 的 Kotlin for 循环需求,需注意避免在 Lambda 表达式中直接使用非局部返回(如 return 未加标签会直接退出外层函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值