首页 > 解决方案 > 如何在 for-each 中继续逻辑?

问题描述

我可以continue在正常的 for 循环中使用。

for (i in 0..10) {
    // .. some initial code
    if (i == something) continue
    // .. some other code
}

但是好像不能用forEach

(0 .. 10).forEach {
    // .. some initial code
    if (i == something) continue
    // .. some other code
}

有没有办法使用类似的continue声明forEach

标签: kotlin

解决方案


从源代码forEach

@kotlin.internal.HidesMembers
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
    for (element in this) action(element)
}

对于集合的每个元素,action都会应用一个 lambda 方法。因此,为了进入for looplambda 方法中的下一个元素,必须完成。并完成它,但必须return在范围内调用:@forEach

(0 .. 10).forEach {
    // .. some initial code
    if (i = something) {
        return@forEach
    }
    // .. some other code
}

推荐阅读