我有这个Kotlin代码,为什么返回@ 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))
Run Code Online (Sandbox Code Playgroud)
我尝试用break @ forEach替换return @ forEach,但Kotlin编译器说:
错误:(785,25)标签'@forEach'不表示循环
如果你想跳出forEach,你应该使用一个运行块:
run breaker@ {
rendered_words.reversed().forEach { rw ->
if (rw.y - the_top > 0 && rw.y - the_top < height) {
new_top = rw.y
return@breaker
}
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法怎么样?
rendered_words.reversed().firstOrNull { rw -> rw.y - the_top > 0 && rw.y - the_top < height }
?.let { new_top = it }
if(new_top != null) {
smoothScrollTo(Math.min(text_y - height, new_top))
}
Run Code Online (Sandbox Code Playgroud)
因为你似乎试图到达这里的是第一个与你的条件匹配的项目,而first/firstOrNull比forEach更好
| 归档时间: |
|
| 查看次数: |
1688 次 |
| 最近记录: |