关于 kotlin foreach 循环的 return 的问题

关于 kotlin foreach 循环的 return 的问题

  1. 直接使用 return,会返回整个包裹循环的调用的函数
val li = arrayListOf(0, 1, 2, 3, 4)
@Test
fun lopperTest() {
    li.forEach {
        if (it == 2) {
            return
        }
        print("$it \t")
    }
    println("\ntest func is end!")
}

// 结果
// 0    1 
  1. 使用 return@XXX 中断本次执行,继续下次循环,类似于 continue
val li = arrayListOf(0, 1, 2, 3, 4)
@Test
fun lopperTest() {
    li.forEach {
        if (it == 2) {
            return@forEach
        }
        print("$it \t")
    }
    println("\ntest func is end!")
}

// 结果
// 0    1   3   4   
// test func is end!
val li = arrayListOf(0, 1, 2, 3, 4)
@Test
fun lopperTest() {
    li.forEach tag@{
        if (it == 2) {
            return@tag
        }
        print("$it \t")
    }
    println("\ntest func is end!")
}

// 结果
// 0    1   3   4   
// test func is end!
  1. 在外面嵌套一个 lambda 表达式并添加标签,实现类似 break 的操作
val li = arrayListOf(0, 1, 2, 3, 4)
@Test
fun lopperTest() {
    run tag@{
        li.forEach {
            if (it == 2) {
                return@tag
            }
            print("$it \t")
        }
    }
    println("\ntest func is end!")
}


// 结果
// 0    1   
// test func is end!

注意:

  1. 不添加标签是不行的
  2. 可以是任意 lambda 表达式,不仅限于例子中的 run
val li = arrayListOf(0, 1, 2, 3, 4)
@Test
fun lopperTest() {
    run {
        li.forEach {
            if (it == 2) {
                return
            }
            print("$it \t")
        }
    }
    println("\ntest func is end!")
}

// 结果
// 0    1
val li = arrayListOf(0, 1, 2, 3, 4)
var aaa: String? = null
@Test
fun lopperTest() {
    aaa = "111"
    aaa?.apply tag@{
        li.forEach {
            if (it == 2) {
                return@tag
            }
            print("$it \t")
        }
    }
    println("\ntest func is end!")
}

// 结果
// 0    1
// test func is end!
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容