Why non local return from inline function returns from lambda but proceed inline function execution?

28 Views Asked by At

Can't understand kotlin logic. For sush code

inline fun inlined( block: () -> Unit) {
    block()
    
    println("hi!")
}
fun foo() {
    inlined {     
        println("5")
        return@inlined // OK: the lambda is inlined
        println("5")
    }
    println("6")
}
fun main() {
    foo()
}

Expected such output "56" but got "5hi!6". How could this happen? And on my understanfing it contradicts following description from documentation enter image description here

Can someone explain it?

UPDATE: Thanks for your answers. I still wandering why execustion of inlined() proceed after calling return@inlined? Anyway lambda is not aware about "inlined()" paremeter "block" but behaves like return@block was called.

1

There are 1 best solutions below

2
Tenfour04 On

You are not doing a non-local return. You are doing a local return, because you used @inlined. The local return returns from the lambda, so code execution continues from after block was called inside the inlined() function. The next line is println("hi!"). Then inlined() returns and code continues execution inside the foo() function.

If you did a non-local return by calling return instead of return@inlined, then the only thing you would see in the console is 5. The println("6") code would never be reached since you would be directly returning from foo().