y
09/15/2022, 10:49 AMreturn@
. why is it needed? does it allow you to do something you previously couldn’t, or is it just syntax sugar?Joffrey
09/15/2022, 10:52 AMreturn
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:
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.ephemient
09/15/2022, 10:52 AMephemient
09/15/2022, 10:52 AMKlitos Kyriacou
09/15/2022, 11:05 AM== 3
be >= 3
in doStuff2, or the comment be // not printed for 3
?Joffrey
09/15/2022, 5:12 PM