DEV Community

Cover image for Lambdas Aren’t Free: A Bytecode Tour of Kotlin’s inline and reified
Android Expert
Android Expert

Posted on Originally published at Medium

Lambdas Aren’t Free: A Bytecode Tour of Kotlin’s inline and reified

Why list.map {} doesn't allocate, but your own higher-order function does.

Open any Android codebase and you will find a utility like this one:

fun measure(block: () -> Unit) {
    val start = System.nanoTime()
    block()
    Log.d("perf", "took ${System.nanoTime() - start} ns")
}
Enter fullscreen mode Exit fullscreen mode

It looks harmless. Now call list.map { it.id } somewhere else in the same file. Same shape: a function that takes a lambda. Yet one of these allocates on every call and the other does not, and the difference has nothing to do with the JIT or with "Kotlin being smart." It comes down to one keyword the standard library uses and your helper does not.

This post goes from the keyword to the bytecode, then to the feature that only exists because of it: reified. Along the way we will cover where inlining backfires, because it does, and often in code review comments like "why did our APK grow 300 KB?"

A note on the listings. The bytecode below is real javap -c -p output from Kotlin 2.0.21, trimmed for space (null-check intrinsics removed). Exact output varies with the Kotlin version and compiler flags, and Android adds its own step on top (see section 1), so reproduce it on your own project with Tools → Kotlin → Show Kotlin Bytecode before quoting it in a design doc.

1. The hidden cost of a lambda

Let’s use a slightly less trivial caller, because the interesting costs show up when the lambda touches its surroundings:

fun countClicks(items: List<Item>): Int {
    var count = 0
    measure { count += items.size }
    return count
}
Enter fullscreen mode Exit fullscreen mode

The lambda reads items and mutates count. The JVM has no concept of a closure, so the compiler has to fake one. Two things get allocated before measure even starts:

  1. A wrapper for the mutated variable. A Java lambda can only capture effectively-final values, but Kotlin lets you write to count. The compiler moves count into a heap object, kotlin.jvm.internal.Ref.IntRef, and both the outer function and the lambda share that box.
  2. The lambda object itself. A Function0<Unit> instance that holds references to the IntRef and to items.

Then measure runs, and calls block.invoke() through the Function0 interface.

lambda-cost

Two honest caveats, because “lambdas allocate” is only half the story:

  • Non-capturing lambdas are free. list.forEach(::println) or measure { Log.d("x", "y") } captures nothing, so the compiler can create one instance and reuse it. The allocation cost is specifically about capturing lambdas, and it is paid every time the lambda expression is evaluated, which for a click handler or a onBindViewHolder is a lot.
  • The lambda’s plumbing depends on the toolchain. Since Kotlin 2.0, the JVM class file expresses a lambda as an invokedynamic instruction bootstrapped by LambdaMetafactory instead of one synthetic class per lambda. Android's runtime has no LambdaMetafactory, though: D8 desugars those call sites back into generated classes when it builds your DEX. So on a device you still pay for a lambda class and an instance, and either way a capturing lambda needs an object holding its captured state. The Ref.IntRef wrapper for mutated locals is also still there.

On Android you will not usually notice one such allocation. You notice thousands of them inside a RecyclerView bind, a Compose recomposition, or a tight loop in a parser, where each one adds GC pressure and an extra indirect call the JIT or ART's compiler may not see through.

2. What inline does

Mark the function inline and the compiler stops treating measure as something to call:

inline fun measure(block: () -> Unit) {
    val start = System.nanoTime()
    block()
    Log.d("perf", "took ${System.nanoTime() - start} ns")
}
Enter fullscreen mode Exit fullscreen mode

At every call site the compiler performs two copies:

  1. The body of measure is pasted into the caller.
  2. The body of the lambda is pasted where block() was.

inline-expansion

Since the lambda body is now just statements in the caller, there is nothing to allocate. count is back to being an ordinary local, because no separate object needs to share it.

That is the entire answer to the hook. list.map {}, filter, forEach, let, apply, use, and synchronized are all declared inline in the standard library. Your measure was not, so it pays the full price. (Not everything lambda-shaped is inline: lazy { } stores its initializer inside the Lazy object, so it cannot be.)

3. Decompiled bytecode, side by side

First the non-inline version of countClicks, as javap -c -p prints it (comments are mine):

public static final int countClicks(java.util.List<Item>);
    new           kotlin/jvm/internal/Ref$IntRef    // allocation #1: the box for `count`
    dup
    invokespecial Ref$IntRef."<init>":()V
    astore_1
    aload_1
    aload_0
    invokedynamic invoke:(Ref$IntRef, List)Function0 // allocation #2: the lambda object
    invokestatic  measure:(Function0)V              // a real call
    aload_1
    getfield      Ref$IntRef.element:I
    ireturn

private static final kotlin.Unit countClicks$lambda$0(Ref$IntRef, java.util.List);
    // the lambda body lives in its own method: element += items.size()
Enter fullscreen mode Exit fullscreen mode

And the inline version, same source apart from the inline keyword:

public static final int countClicks(java.util.List<Item>);
    iconst_0
    istore_1                         // `count` is a plain int local
    invokestatic  System.nanoTime    // body of measure() starts here...
    lstore_3
    iload_1
    aload_0
    invokeinterface List.size        // ...and the lambda body is already in place
    iadd
    istore_1
    invokestatic  System.nanoTime    // rest of measure()
    lload_3
    lsub
    ...                              // println(...)
    iload_1
    ireturn
Enter fullscreen mode Exit fullscreen mode

No Ref$IntRef, no invokedynamic, no call to measure. On a JVM that is the whole difference. On Android, remember that D8 turns the invokedynamic in the first listing into a generated class, so the non-inline version costs you a class in the DEX too.

bytecode-comparison

One detail surprises people: the measure method still exists in the class file of the inline version (javap -p lists public static final void measure(Function0<Unit>) even there). The compiler keeps a real method so Java callers, reflection, and binary compatibility with older compiled code keep working. Kotlin call sites just never use it.

A word on the “faster” claim. You are removing allocations and an indirect call; you are not guaranteeing a measurable speedup. If measure runs once per screen, you will see nothing. If it runs per frame or per item, you might. Profile before you rewrite anything, and use Android Studio's allocation tracking or Perfetto rather than intuition.

4. When inlining backfires

Inlining trades runtime cost for code size, and the exchange rate gets ugly quickly.

Code bloat

The body is copied once per call site. In the worst case, a 150-instruction function called from 25 places adds 3,750 instructions to your app, while the same function left alone costs 150. Treat that as an upper bound: D8 and R8 can trim dead code and fold constants in each copy, so measure the real delta in your APK before and after.

inline-backfire

On Android the symptoms are concrete: a larger DEX, a higher method-size risk (the JVM caps a single method at 64 KB of bytecode, and a method that inlines several big functions inside a loop can reach it), worse instruction-cache behavior, and slower builds. R8 can outline some repeated sequences and prune dead code, but it does not systematically reverse inlining, so do not count on it to clean up after you.

Compiler warnings you should believe

If you mark a function inline that takes no lambda parameter, Kotlin tells you the expected performance impact is insignificant. It is right. There is no allocation to remove, so you are copying code for nothing. Legitimate exceptions are reified type parameters and, rarely, deliberately removing a call from a stack trace.

Public API stability

This is the failure mode that bites library authors. A public inline function's body is compiled into every consumer's bytecode. Ship a bug fix in version 1.2 and apps built against 1.1 keep the bug until they recompile, even if they update the dependency at runtime.

The visibility rules reflect this. A public inline function cannot touch non-public API, because the pasted code has to compile in someone else’s module. The escape hatch is @PublishedApi:

@PublishedApi
internal fun recordTiming(name: String, nanos: Long) { /* ... */ }

inline fun <T> trace(name: String, block: () -> T): T {
    val start = System.nanoTime()
    try {
        return block()
    } finally {
        recordTiming(name, System.nanoTime() - start)
    }
}
Enter fullscreen mode Exit fullscreen mode

recordTiming is effectively public in bytecode, so you have just frozen its signature. Treat @PublishedApi members as public API.

Smaller papercuts

  • Debugging. Stack traces and breakpoints inside inlined code point at synthetic line mappings. It works, but it is more confusing than a normal frame.
  • No recursion. An inline function cannot call itself, since the expansion would never end.
  • Lambda parameters are restricted. A plain inline lambda parameter cannot be stored in a field or passed to a non-inline function. That is what the next section addresses.

5. noinline and crossinline

Inlining a lambda means its body is spliced into the function. That only works if the lambda is used in a way the compiler can splice. Two modifiers handle the cases where it is not.

noinline-crossinline

noinline: "I need this to be a real object"

If you pass the lambda to something that expects an actual Function instance, or store it, it cannot be pasted. Mark it noinline and it behaves like a normal lambda while the other parameters stay inlined.

class ErrorDispatcher {
    // An ordinary, non-inline function: it wants a real Function object.
    fun dispatch(error: Exception, handler: (Exception) -> Unit) {
        Log.e("guarded", "operation failed", error)
        handler(error)
    }
}

inline fun <T> ErrorDispatcher.guarded(
    noinline onError: (Exception) -> Unit,   // handed to dispatch() as a value
    block: () -> T,                          // stays inlined
): T? =
    try {
        block()
    } catch (e: Exception) {
        dispatch(e, onError)                 // passing it along needs noinline
        null
    }
Enter fullscreen mode Exit fullscreen mode

Without noinline, the dispatch(e, onError) line is a compile error, because an inlined lambda has no object to hand over. The tradeoff: onError is allocated like any lambda, but block (usually the hot part) is not. Notice that dispatch uses the handler immediately and forgets it. Be careful with the variant that stores a noinline lambda, for example appending it to a list on every call: that retains the lambda and everything it captured, which is a classic memory leak. A bonus use: noinline is how you make an inline function's lambda parameter nullable.

One more caveat on the example: catching Exception is deliberate. Catching Throwable would also swallow OutOfMemoryError, and in coroutine code you should rethrow CancellationException instead of reporting it.

crossinline: "inline it, but don't let it return from me"

A plain inline lambda may use return to exit the enclosing function (a non-local return). That is only safe if the lambda runs directly in the function body. If the inline function calls the lambda from inside another lambda or object, such as a click listener, a Runnable, or a coroutine, the call may happen after the enclosing function has finished. The compiler refuses that unless you promise there is no non-local return:

inline fun View.setSafeClickListener(
    intervalMs: Long = 600,
    crossinline onSafeClick: (View) -> Unit,
) {
    var lastClick = 0L
    setOnClickListener { view ->
        val now = SystemClock.elapsedRealtime()
        if (now - lastClick >= intervalMs) {
            lastClick = now
            onSafeClick(view)       // runs inside another lambda: needs crossinline
        }
    }
}

// call site
binding.buy.setSafeClickListener { v ->
    // `return` here would not compile: it cannot exit the caller
    viewModel.onBuyTapped(v.id)
}
Enter fullscreen mode Exit fullscreen mode

Two real-world warnings about this exact helper:

  1. The body is still copied. The onSafeClick body is pasted into the anonymous listener that setOnClickListener receives, which means each call site generates its own listener class. You saved nothing on allocation (the listener object exists anyway) and added code per call site. For UI event wiring, a non-inline version is often the better choice.
  2. lastClick is captured and mutated, so it lives in a Ref.LongRef. Inlining does not remove that here, because the variable genuinely outlives the function call.

6. Type erasure, then reified

On the JVM, generic type arguments exist at compile time and mostly vanish at runtime. A List<String> and a List<Int> are the same class, java.util.List, once compiled. So this cannot work:

fun <T> parse(json: String): T {
    // val type = T::class.java      // compile error: cannot use T as a reified type parameter
    // if (value is T) { ... }       // compile error for the same reason
    TODO()
}
Enter fullscreen mode Exit fullscreen mode

Inside parse, the runtime does not know what T is, because parse was compiled once for all T.

inline changes the premise. If the function body is copied into each call site, the compiler knows the concrete type at each copy. Marking the parameter reified tells it to substitute that type in place:

inline fun <reified T> parse(json: String): T { /* T::class.java now works */ }
Enter fullscreen mode Exit fullscreen mode

reified-pipeline

At the call parse<User>(json), the pasted body contains the User class constant directly. Nothing about the JVM changed. The compiler did the substitution before the bytecode was written, which is why reified requires inline: without the copy, there is nowhere to put the concrete type.

Consequences worth remembering:

  • A reified function cannot be called from Java, because Java has no way to supply the inlined type.
  • You can only pass a concrete type or another reified parameter as the argument. Calling parse<T>(json) from a normal fun <T> is a compile error, since that T is erased.
  • Reified is a compile-time rewrite, not a runtime capability.

7. Practical reified use cases

Gson without the Class argument

The classic. Gson needs a Type to deserialize generics like List<User>, and you get it by capturing a TypeToken subclass. Wrap that once:

inline fun <reified T : Any> Gson.fromJson(json: String): T =
    fromJson(json, object : TypeToken<T>() {}.type)
        ?: error("Empty or null JSON for ${T::class.java.simpleName}")

// usage
val user: User = gson.fromJson(payload)
val users: List<User> = gson.fromJson(payload)   // generic type preserved
Enter fullscreen mode Exit fullscreen mode

Why it works for List<User>: because the body is inlined, the anonymous TypeToken<T> subclass is created at the call site with T already replaced by List<User>, and the subclass's generic superclass carries that full type.

Failure mode: Gson returns null for an empty string or a literal null, and returns platform types in Kotlin. Without the ?: error(...) guard, a T : Any can silently hold null and crash later, far from the cause. Gson also bypasses Kotlin constructors and default values, so non-null fields can be null after parsing. Moshi or kotlinx.serialization (which has its own inline fun <reified T> decodeFromString) avoid this class of bug.

Intent and Bundle extras

Android 13 (API 33) deprecated the untyped getParcelableExtra(String) in favor of an overload that takes the class. IntentCompat from androidx.core already contains the version fork, so the helper only has to supply the class, and that is exactly the part reified provides:

import androidx.core.content.IntentCompat

inline fun <reified T : Parcelable> Intent.parcelable(key: String): T? =
    IntentCompat.getParcelableExtra(this, key, T::class.java)

// usage
val order: Order? = intent.parcelable("order")
Enter fullscreen mode Exit fullscreen mode

Without reified, every caller would write intent.parcelable("order", Order::class.java), repeating a type the compiler already knows. If you cannot take the AndroidX dependency, you end up hand-rolling an SDK_INT check with a @Suppress("DEPRECATION") branch for older devices, and on that branch the cast as? T is only a real runtime check because T is reified. A non-reified version would compile to an unchecked cast and fail later with a ClassCastException somewhere unrelated. Prefer IntentCompat (or BundleCompat for bundles) over that hand-rolled fork.

startActivity<T>()

inline fun <reified T : Activity> Context.startActivity(
    configure: Intent.() -> Unit = {},
) {
    startActivity(Intent(this, T::class.java).apply(configure))
}

// usage
context.startActivity<DetailActivity> {
    putExtra("order_id", orderId)
}
Enter fullscreen mode Exit fullscreen mode

The default value on configure (= {}) is allowed on an inline function's lambda parameter in current Kotlin; I compiled this exact signature with 2.0.21. Very old compilers (before 1.2) rejected defaults on inline lambdas, so if you maintain legacy code you may meet noinline or overloads used as a workaround.

Failure mode: if this is an application context or a service rather than an Activity, Android throws AndroidRuntimeException unless the intent carries FLAG_ACTIVITY_NEW_TASK. The helper makes the call look safe everywhere, so the crash shows up on the one path that passes the wrong context.

8. Rule of thumb

inline-decision-guide

In plain words:

  • Inline when the function takes a lambda, the body is small, and it runs often enough to matter (collection operators, scoping helpers, resource wrappers such as trace, measure, withTransaction). Also inline when you want non-local return from the lambda.
  • Inline when you need reified. That is the one case where it is not an optimization but a requirement.
  • Leave it alone when there is no lambda parameter, the body is large, the function is recursive, or you need to store or pass the lambda around. If a big function has a hot lambda, keep the big part as a normal function and wrap it with a small inline entry point.
  • Be strict with public library API. Every public inline function freezes its body into your users' builds. Keep it tiny, keep what it touches behind @PublishedApi, and re-test binary compatibility when you change it.
  • Measure. The wins are removed allocations and indirect calls; the costs are DEX size and compile time. Android Studio’s allocation tracking, Perfetto, and a diff of your APK size will tell you which side you landed on.

So back to the opening question: list.map {} does not allocate because the standard library declared it inline, and the compiler pasted your lambda into the caller. Your measure allocates because it did not. Now you know which one to reach for, and what you pay for it.

📱 Stop Guessing Whether Your Android Code Actually Works

If “we’ll add tests later” is a sentence your team says a little too often, I’d recommend “Mastering Android Testing” — a 35-chapter deep dive into why Android testing is uniquely hard (Activity/Fragment coupling, async complexity, tooling churn) and exactly how to fix it, layer by layer. It walks through architecting for testability, JUnit/Truth/MockK fundamentals, ViewModel and coroutine/Flow testing without flakiness, Compose UI testing and the semantics tree, Espresso and instrumented tests, Room/Retrofit data-layer testing with a full sync-conflict-resolution case study, Robolectric’s real limits, CI pipelines, flaky test triage, and how to build a testing culture that actually survives contact with a deadline.


Originally published on Medium.

Top comments (0)