如何在for-each中继续逻辑?

时间:2018-07-15 12:12:26

标签: kotlin

我可以在普通的for循环中使用continue

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语句?

2 个答案:

答案 0 :(得分:1)

来自forEach的源代码:

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

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

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

答案 1 :(得分:0)

使用return@forEach代替continue