Careeroza
noinline and crossinline
Fine Control
| Modifier | Meaning | Needed when |
|---|---|---|
noinline | this lambda stays a real object | you store it or pass it to a non-inline function |
crossinline | lambda is inlined but non-local return is forbidden | you call it from another context (a nested lambda, Runnable, another thread) |
Example
val callbacks = mutableListOf<() -> Unit>()
inline fun register(onNow: () -> Unit, noinline onLater: () -> Unit) {
onNow()
callbacks += onLater // storing needs a real object: noinline
}
inline fun runInWrapper(crossinline body: () -> Unit): Runnable =
Runnable { println("before"); body(); println("after") } // called from another object
fun main() {
register(onNow = { println("runs immediately") }, onLater = { println("runs later") })
callbacks.forEach { it() }
runInWrapper { println("inside wrapper") }.run()
}Output
runs immediately runs later before inside wrapper after