I have this Kotlin code, why return@forEach doesn't jump out of forEach? It continues the loop until it finishes, removing reversed() doesn't solve problem:
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))
I tried replacing return@forEach with break@forEach but Kotlin compiler says :
Error:(785, 25) The label '@forEach' does not denote a loop
If you want to jump out of forEach, you should use a run 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
}
}
}
How about this approach?
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))
}
because what you seem to try to get here is the first item that matches your condition, and the first/firstOrNull is better there than the forEach
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With