noinline and crossinline

Fine Control

ModifierMeaningNeeded when
noinlinethis lambda stays a real objectyou store it or pass it to a non-inline function
crossinlinelambda is inlined but non-local return is forbiddenyou 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