Junior — Middle
Is it possible to perform a return from a function outside the current context inside a function declared as crossinline in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, a function declared with the crossinline modifier prohibits the execution of non-local returns from the lambda it accepts. This means that you cannot use return inside the lambda to exit from the outer function in which this lambda is called.
Example:
inline fun foo(crossinline block: () -> Unit) {
val runnable = Runnable {
block() // non-local return cannot be used here
}
runnable.run()
}
fun bar() {
foo {
// return // compilation error, non-local return is not allowed
println("Executing lambda")
}
println("Continuing in function bar")
}
Thus, returning from a function outside the current context inside a crossinline lambda is impossible. This restriction is introduced for safety and predictability of the code, especially when using lambdas in asynchronous or deferred calls.