Part 15 / Topic 3 of 6
How lambdas and inline functions compile
A lambda is a value with a function type (Part 10) -- (Int) -> Int -- and on the JVM it has to
become some kind of object, because the JVM has no native "function value." An ordinary,
non-inline call allocates exactly that: an object implementing kotlin.jvm.functions.Function1,
built through invokedynamic (the JVM instruction behind Java's own lambdas), then invoked
through one interface call.
fun applyNonInline(x: Int, f: (Int) -> Int): Int = f(x)
inline fun applyInline(x: Int, f: (Int) -> Int): Int = f(x)
fun main() {
println(applyNonInline(5) { it * 2 })
println(applyInline(5) { it * 2 })
}
javap -c on main shows the difference directly. The non-inline call builds a lambda object
and calls through the interface:
0: iconst_5
1: invokedynamic #59, 0 // InvokeDynamic #0:invoke:()Lkotlin/jvm/functions/Function1;
6: invokestatic #61 // Method applyNonInline:(ILkotlin/jvm/functions/Function1;)I
The inline call has no lambda, no object, and no call to applyInline at all -- the compiler
pasted the lambda's body (it * 2, i.e. * 2) straight into main:
17: iconst_5
18: istore_0
...
25: iload_2
26: iconst_2
27: imul // the lambda body, inlined directly: no object, no call
That's the entire story of inline: zero allocation, zero indirection, because there's nothing
left to allocate or call through by the time the class file exists. It's also why reified type
parameters (Part 13) need inline -- the type argument has to be known as literal bytecode at
every call site, which is only possible once the function body is copied there.
noinline and crossinline
"Paste the lambda's body in" has two situations where it can't just happen as-is, so Kotlin needs two parameter modifiers to say so explicitly:
inline fun runTwice(noinline onDone: () -> Unit, crossinline onEach: () -> Unit) {
val savedForLater = onDone // only legal because onDone is `noinline`
repeat(2) {
Runnable { onEach() }.run() // only legal because onEach is `crossinline`
}
savedForLater()
}
Remove both modifiers and kotlinc refuses, with the exact reason in the error:
error: illegal usage of inline parameter 'onDone: () -> Unit'. Add 'noinline' modifier to the
parameter declaration.
val saved = onDone
error: cannot inline 'onEach: () -> Unit' here: it might contain non-local returns. Add
'crossinline' modifier to parameter declaration 'onEach: () -> Unit'.
Runnable { onEach() }.run()
noinline keeps one parameter as a genuine function object -- needed the moment you want to
store it, return it, or pass it somewhere else, instead of calling it directly where it was
given. crossinline allows a parameter to be called from inside another lambda (the Runnable
above), while still forbidding it from doing a non-local return out of the outer function --
only the directly-inlined parts of an inline function get that non-local power.
Non-local break/continue (and return) through an inline lambda
Because an inline lambda's body is pasted directly into the caller, break, continue, and
return written inside it affect the enclosing loop or function, not just the lambda itself:
val amountsInr = listOf(100, 250, 400, 50, 900)
for (amount in amountsInr) {
amount.let {
if (it > 300) {
println("stopping at $it")
break // breaks the for loop below, not just the `let`
}
println("ok: $it")
}
}
println("loop finished")
ok: 100
ok: 250
stopping at 400
loop finished
let is itself an inline function from the standard library, so this isn't special-cased
syntax -- it's the same mechanism as runTwice above, just with the standard library's own
inline function instead of a hand-written one.
Full program: examples/03_lambdas_and_inline_functions.kt.
Done here? The practice set for Part 15 — including the solutions — is on the part page.