欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > Kotlin for 循环核心用法与进阶操作(2025 版)

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

2025/4/5 10:02:42 来源:https://blog.csdn.net/qq_25462179/article/details/146984030  浏览:    关键词: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 未加标签会直接退出外层函数。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词