Why we need noinline in kotlin?
Asked Answered
N

2

6

I'm reading kotlin doc and can't understend one thing.

We can use noinline modifier to mark that lambda shouldn't be inline. But what is the real case when we really need it?

I understend what noinline does, but can't understand why.

Neocolonialism answered 31/1, 2022 at 8:13 Comment(0)
M
8

Notice that when inline is added to a function/method declaration, all of its lambda parameters are inlined.

Also notice that there are some ways in which you can use a lambda parameter, that requires the lambda to be not inlined. For example, passing it to another, non-inlined function, or assigning it to a variable:

var func: (() -> Unit)? = null
inline fun foo(x: () -> Unit, y: () -> Unit) {
    notInlined(x) // x must be not inlined for this to work
    func = x // x must be not inlined for this to work
}

So what if I want to do notInlined(x), but I still want to inline y? This is where I use noinline:

inline fun foo(noinline x: () -> Unit, y: () -> Unit)

IntelliJ even gives this as a suggestion:

enter image description here

Milzie answered 31/1, 2022 at 8:46 Comment(0)
K
0

One thing I notice is that this for example is allowed, but "end of runLambda" is never reached then.

fun main() {
    runLambda {
        println("lambda")
        return
    }

}

inline fun runLambda(lambda: ()->Unit) {
    lambda.invoke()
    println("end of runLambda")
}

if you want to ensure that the function completely runs until the end noinline could fix it because then it won't allow the return

enter image description here

Although crossinline can do the same and I think that one is actually meant for that. I'm not sure what the difference is

Kapor answered 31/1, 2022 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.