微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Kotlin 中 `forEach` 中的 `break` 和 `continue`

如何解决Kotlin 中 `forEach` 中的 `break` 和 `continue`

: 根据 Kotlin 的文档,可以continue使用注释进行模拟。

fun foo() {
    listof(1, 2, 3, 4, 5).forEach lit@ {
        if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop
        print(it)
    }
    print(" done with explicit label")
}

如果要模拟 a break,只需添加一个run

fun foo() {
    run lit@ {
        listof(1, 2, 3, 4, 5).forEach {
            if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop
            print(it)
        }
        print(" done with explicit label")
    }
}

: 既然你提供了 a (Int) -> Unit,你就不能摆脱它,因为编译器不知道它是在循环中使用的。

你有几个选择:

for (index in 0 until times) {
    // your code here
}

您可以使用return它来退出方法(或者return value如果它不是unit方法)。

创建一个自定义的重复方法方法,该方法返回Boolean以继续。

public inline fun repeatUntil(times: Int, body: (Int) -> Boolean) {
    for (index in 0 until times) {
        if (!body(index)) break
    }
}

解决方法

Kotlin 有非常好的迭代函数,比如forEachor
repeat,但我无法让breakandcontinue运算符与它们一起工作(本地和非本地):

repeat(5) {
    break
}

(1..5).forEach {
    continue@forEach
}

目标是用尽可能接近的函数语法来模拟通常的循环。在某些旧版本的 Kotlin 中绝对可以,但我很难重现语法。

问题可能是标签(M12)的错误,但我认为第一个示例无论如何都应该有效。

在我看来,我在某处读过一个特殊的技巧/注释,但我找不到关于这个主题的任何参考资料。可能如下所示:

public inline fun repeat(times: Int,@loop body: (Int) -> Unit) {
    for (index in 0..times - 1) {
        body(index)
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。