在Kotlin,'return'并没有跳出forEach

AVE*_*imi 4 android kotlin

我有这个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'不表示循环

AVE*_*imi 9

如果你想跳出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)

  • 您可以使用 return@run ,不需要显式提供 Breaker@ (3认同)

koc*_*cka 4

这种方法怎么样?

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更好

  • 它不需要使用 `let`,`.firstOrNull{}?.smoothScrollTo()` 就可以。 (4认同)