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.
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.
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:
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
Although crossinline
can do the same and I think that one is actually meant for that. I'm not sure what the difference is
© 2022 - 2024 — McMap. All rights reserved.