gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:38:12 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





`break` and `continue` in `forEach` in Kotlin

(10 个回答)


3年前关闭。




我可以使用 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 的声明?

最佳答案

来自 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
}

关于kotlin - 如何在 for-each 中继续逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51348262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com