Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'return' doesn't jump out of forEach in Kotlin

Tags:

android

kotlin

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

like image 759
AVEbrahimi Avatar asked Jan 02 '18 07:01

AVEbrahimi


2 Answers

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
        }
    }
}
like image 120
AVEbrahimi Avatar answered Oct 27 '22 01:10

AVEbrahimi


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

like image 30
kocka Avatar answered Oct 27 '22 01:10

kocka