Kotlin return与return@forEachIndexed

Kotlin return与return@forEachIndexed

Kotlin 复制代码
fun main() {
    val data = arrayOf(0, 1, 2, 3, 4)

    println("a")

    data.forEachIndexed { index, v ->
        if (v == 2) {
            //类似while循环中的continue
            //跳过,继续下一个forEachIndexed迭代
            return@forEachIndexed
        }

        println("a index=$index $v")
    }

    println("b")

    data.forEachIndexed { index, v ->
        if (v == 2) {
            //这是退出整个main函数。
            return
        }

        println("b index=$index $v")
    }

    println("这里运行不到")
}

a

a index=0 0

a index=1 1

a index=3 3

a index=4 4

b

b index=0 0

b index=1 1

Process finished with exit code 0

kotlin forEachIndexed arrayListOf<String>_kotlin arraylist foreach-CSDN博客文章浏览阅读184次。Python for循环中的zip_python zip函数用于for循环_zhangphil的博客-CSDN博客。_kotlin arraylist foreachhttps://blog.csdn.net/zhangphil/article/details/131003571kotlin forEach循环return/break_kotlin foreach return-CSDN博客文章浏览阅读1.3k次。该文章通过代码示例展示了在Kotlin中如何在forEachIndexed循环中使用return和自定义标签的break,以及其对循环控制的影响。示例解释了如何在遇到特定条件时提前退出循环并添加元素到另一个列表。https://blog.csdn.net/zhangphil/article/details/131659989

相关推荐
投笔丶从戎1 小时前
Kotlin Multiplatform--01:项目结构基础
android·开发语言·kotlin
_一条咸鱼_4 小时前
深度剖析 Android ViewPager:从源码探究其使用原理
android·面试·kotlin
每次的天空6 小时前
kotlin与MVVM结合使用总结(三)
开发语言·microsoft·kotlin
louisgeek19 小时前
Kotlin 面试知识点
kotlin
Kapaseker1 天前
Kotlin泛型精解:类型世界的奇幻之旅
android·kotlin
居然是阿宋1 天前
Kotlin函数体详解:表达式函数体 vs 代码块函数体——使用场景与最佳实践
java·开发语言·kotlin
划水哥~1 天前
Kotlin中实现静态
开发语言·kotlin
tangweiguo030519872 天前
Android Kotlin AIDL 完整实现与优化指南
android·kotlin
Lei活在当下2 天前
Kotlin协程浅入浅出
kotlin
alexhilton3 天前
深入理解Jetpack Compose中的函数的执行顺序
android·kotlin·android jetpack