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

相关推荐
Kapaseker3 小时前
Compose 中实现凸角、凹角、切角、尖角
android·kotlin
yueqc110 小时前
Kotlin 协程 Flow 操作符总结
kotlin·协程·flow
molong93115 小时前
Kotlin 内联函数、高阶函数、扩展函数
android·开发语言·kotlin
低调小一19 小时前
Kuikly 小白拆解系列 · 第1篇|两棵树直调(Kotlin 构建与原生承载)
android·开发语言·kotlin
Android-Flutter1 天前
kotlin - 正则表达式,识别年月日
java·kotlin
ROO_KIE1 天前
[Java、C语言、Python、PHP、C#、C++]——深度剖析主流编程语言的核心特性与应用场景
kotlin
alexhilton2 天前
Kotlin互斥锁(Mutex):协程的线程安全守护神
android·kotlin·android jetpack
太过平凡的小蚂蚁2 天前
Kotlin 异步数据流三剑客:Flow、Channel、StateFlow 深度解析
android·kotlin
铉铉这波能秀3 天前
如何在Android Studio中使用Gemini进行AI Coding
android·java·人工智能·ai·kotlin·app·android studio