hey, coming from other languages, I’m struggling t...
# getting-started
y
hey, coming from other languages, I’m struggling to see use cases for
return@
. why is it needed? does it allow you to do something you previously couldn’t, or is it just syntax sugar?
j
It is useful because Kotlin has non-local returns. Basically if you're in a lambda, a plain
return
would return from the closest enclosing function declared with
fun
keyword - not only from the lambda. If you want to only return from the lambda call and not from the enclosing function, you have to use a labeled return. For instance:
Copy code
fun doStuff() {
    listOf(1, 2, 3, 4, 5).forEach {
        println("Processing $it")
        if (it == 3) {
            return
        }
        println("Done with $it")
    }
    println("I'm not printed because we returned from doStuff(), not from forEach's lambda")
}

fun doStuff2() {
    listOf(1, 2, 3, 4, 5).forEach {
        println("Processing $it")
        if (it == 3) {
            return@forEach
        }
        println("Done with $it") // not printed for 3
    }
    println("I am printed because we only returned from the forEach lambda")
}
Also note that in the second case we still call the lambda on all 5 elements. The
return@forEach
only returns from the current invocation of the lambda that we passed to
forEach
but it doesn't prevent the implementation of
forEach
from continuing the loop and calling the lambda a few more times. That is why
Processing X
is printed for all 5 elements, and
Done with X
is printed for all but element 3.
☝️ 2
👍 1
e
sometimes it helps with disambiguation, but usually it enables code that could not otherwise be expressed
k
Should the
== 3
be
>= 3
in doStuff2, or the comment be
// not printed for 3
?
j
Good catch, thanks. Edited.
👍 1