August 2018
Beginner
178 pages
4h 56m
English
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 ...
Read now
Unlock full access