Returns and jumps
Kotlin has three structural jump expressions:
returnby default returns from the nearest enclosing function or anonymous function.breakterminates the nearest enclosing loop.continueproceeds to the next step of the nearest enclosing loop.
break and continue labels
Any expression in Kotlin may be marked with a label.
Labels have the form of an identifier followed by the @ sign, such as abc@ or fooBar@.
To label an expression, just add a label in front of it.
Now, we can qualify a break or a continue with a label:
A break qualified with a label jumps to the execution point right after the loop marked with that label.
A continue proceeds to the next iteration of that loop.
return to labels
In Kotlin, functions can be nested using function literals(lambda expressions), local functions, and object expressions(inline objects).
Qualified returns allow us to return from an outer function.
The most important use case is returning from a lambda expression.
Recall that when we write the following, the return expression returns from the nearest enclosing function foo:
To return from a lambda expression, label it and qualify the return:
Now, it returns only from the lambda expression.
Often it is more convenient to use implicit labels, because such a label has the same name as the function to which the lambda is passed.
Alternatively, you can replace the lambda expression with an anonymous function.
A return statement in an anonymous function will return from the anonymous function itself.
There is no direct equivalent for break, but it can be simulated by adding another nesting lambda and non-locally returning from it:
Therefore, code can be rewritten as (using the implicit label):