Johnny N. (3) [Avatar] Offline
#1
I'm currently reading the section in Chapter 8 where it describes how the return@label is similar to Java's break expression in a for loop. I find it hard to see the comparison here because when I use the return@label to exit a .forEach lambda's loop, it doesn't break the loop.

Here is my code snippet:
fun lookForAlice(people: List<Person>) {
    people.forEachIndexed label@{ index, person ->
        if (index == 2) {
            return@label
        }
        // Should exit the lambda after return@label
        println("Index = $index")
    }
    println("Index 2 found")
}

And the output I get is this:
Index = 0
Index = 1
Index = 3
Index = 4
Index = 5
Index = 6
Index 2 found
[1, 2, 3]

Shouldn't the code not print out any indexes after 2 because the return@label exits the lambda after that?
Dmitry Jemerov (39) [Avatar] Offline
#2
The comparison with "break" is indeed confusing; we'll try to change that when the book gets updated. The return@label exits the lambda, but it doesn't interrupt the enclosing 'forEach' function, which will repeatedly call the lambda for subsequent entries in the collection. It's much more similar to how "continue" works in a "for" loop.