Returning from lambdas

Let's imagine that you have a lambda function and you want to exit from it early, like in this example:

fun returnStatement() {
val nums = arrayOf(1, 2, 3, 4, 5)
println("Started iterating the array")
nums.forEach { n ->
if (n > 2) {
return
}
}
println("Finished iterating the array")
}

This code will never print Finished iterating the array. The reason is that the return statement inside the lambda is a non-local return, and it returns from the top-level block and not the block where it is declared. If you think that doesn't make sense, if you use the return statement inside a for statement or a while loop, it would also exit the top-level block, not the loop itself.

Kotlin allows return statements to have labels. You can define your own you label or use the default one, which is the function name. This is how we can fix the previous example to print the last statement with the default return label:

fun returnStatement() {
val nums = arrayOf(1, 2, 3, 4, 5)
println("Started iterating the array")
nums.forEach { n ->
if (n > 2) {
return@forEach
}
}
println("Finished iterating the array")
}

Here's how you would define your own label. Before the lambda block, place the name of your label followed by the @ character:

fun returnStatement() {
val lamdba = label@ {
return@label
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.115.166