Kotlin inline function only have a return statement

Viewed 811

I want to use inline function return outside function(skip print the "after"). So when I use

inline fun test() {
    return
}

fun test1() {
    println("before")
    test()
    println("after")
}
test1()

the output is

before  
after

When I use

inline fun test(callBack: () -> Unit) {
    callBack()
}

fun test1() {
    println("before")
    test {
        return
    }
    println("after")
}
test1()

the output is

before

So I want to know why the return statement in the first inline function is not working. Why does the first block of code not work?

2 Answers

As per documentation:

(return) by default returns from the nearest enclosing function or anonymous function. -- returns-and-jumps

A return statement without a label always returns from the function declared with the fun keyword. -- anonymous-functions

Actually I would revert the question: why does it work in the second example? And the answer is:

In Kotlin, we can only use a normal, unqualified return to exit a named function or an anonymous function. This means that to exit a lambda, we have to use a label, and a bare return is forbidden inside a lambda, because a lambda cannot make the enclosing function return (...). But if the function the lambda is passed to is inlined, the return can be inlined as well, so it is allowed. -- non local returns

you can use kotlin Crossinline

Crossinline allows you to mark a lambda to forbid it from using non-local returns. If you remember, inline lambdas interprets return as non-local returns and return is not allowed on non-inlined lambdas

fun main(args: Array<String>) {
    test1()
}


inline fun test(crossinline callBack: () -> Unit) {
    callBack()
}

fun test1() {
    println("before")
    test {
        return@test
    }
    println("after")
}

then the output will be has expectes

Related