我有这段Kotlin代码,为什么return@forEach没有跳出forEach?它继续循环直到完成,删除 reversed() 并不能解决问题:
rendered_words.reversed().forEach { rw ->
if (rw.y - the_top > 0 && rw.y - the_top < height) {
new_top = rw.y
return@forEach
}
}
smoothScrollTo(Math.min(text_y - height, new_top))
我尝试用 break@forEach 替换 return@forEach 但 Kotlin 编译器说:
Error:(785, 25) The label '@forEach' does not denote a loop
最佳答案
如果你想跳出forEach,你应该使用一个运行 block :
run breaker@ {
rendered_words.reversed().forEach { rw ->
if (rw.y - the_top > 0 && rw.y - the_top < height) {
new_top = rw.y
return@breaker
}
}
}
关于android - 'return' 不会跳出 Kotlin 中的 forEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48056994/