Back in java I used to write only return
for a void method... But kotlin doesn\'t seem to allow just return, instead it uses return@methodname
?
Can som
When inside a lambda, you have to specify which scope you wish to return
from, because it might be ambiguous. See the official docs about returning at labels.
In this specific case, if you'd be returning at the end of a function that returns nothing, you can omit the return
statement altogether.
From kotlinlang website:
Return at Labels
With function literals, local functions and object expression, functions can be nested in Kotlin. 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 this:
fun foo() {
ints.forEach {
if (it == 0) return // nonlocal return from inside lambda directly to the caller of foo()
print(it)
}
}
The return
-expression returns from the nearest enclosing function, i.e. foo. (Note that such non-local returns are supported only for lambda expressions passed to inline functions.) If we need to return from a lambda expression, we have to label it and qualify the return
:
fun foo() {
ints.forEach lit@ {
if (it == 0) return@lit
print(it)
}
}
Now, it returns only from the lambda expression. Oftentimes it is more convenient to use implicits labels: such a label has the same name as the function to which the lambda is passed.
fun foo() {
ints.forEach {
if (it == 0) return@forEach
print(it)
}
}