我可以在普通的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
语句?
答案 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