DEV Community

Cover image for The Wrapper You Never Wrote: Tracking Hidden Boxing of Kotlin Value Classes on Android
Android Expert
Android Expert

Posted on Originally published at Medium

The Wrapper You Never Wrote: Tracking Hidden Boxing of Kotlin Value Classes on Android

Value classes promise type safety at zero cost. That promise has fine print, and on a phone with a 16 ms frame budget the fine print is where your jank lives.

Why this matters

A typed ID is the cheapest bug fix in a Kotlin codebase. Swap Long for UserId, and the compiler stops you from passing a PostId where a UserId belongs. The pitch for @JvmInline value class is that this safety is erased at compile time, so you pay nothing at runtime.

Mostly true. “Mostly” is the problem.

Here is a composite of a review I have seen more than once. A feed screen renders a few hundred rows. Someone migrates raw Long ids to PostId, the diff looks tidy, tests pass, and a later trace shows a new stream of short-lived objects during fling. Nothing is leaking and nothing crashes. The wrapper objects the migration was supposed to eliminate were being created anyway, quietly, at every place the value crossed a generic or nullable boundary.

This post covers when the compiler boxes a value class, why, how to prove it with real tooling instead of intuition, and how to design around it. Everything below assumes a recent Kotlin toolchain targeting ART, and the code is deliberately small so you can paste it into a scratch module and verify each claim.

1. What the compiler actually generates

Start with the smallest possible example:

@JvmInline
value class UserId(val raw: Long) {
    val label: String get() = "user-$raw"
}

fun load(id: UserId): String = id.label
Enter fullscreen mode Exit fullscreen mode

Decompile this (Android Studio: Tools → Kotlin → Show Kotlin Bytecode → Decompile, or run javap -c -p on the class file) and you will find roughly the following shape:

  • A final class UserId with a private long raw field.
  • Static helpers such as constructor-impl(long), toString-impl(long), hashCode-impl(long), equals-impl(long, Object) and equals-impl0(long, long) (used for typed ==).
  • A pair of bridge methods, box-impl(long) and unbox-impl().
  • Your function emitted as load-<hash>(long), taking the raw primitive rather than a UserId.

The <hash> suffix is name mangling. It stops two overloads that differ only by value class from colliding after erasure, and it also makes such functions awkward to call from Java.

Two consequences follow:

  1. The wrapper class always exists. It is simply not used on the fast path.
  2. box-impl is the allocation. Every time the compiler needs a real UserId object, it calls box-impl, which executes new UserId(raw). Hunting hidden boxing means hunting for calls to that method.

The rest of this article is the set of situations in which the compiler is forced to call it.

2. The boxing rules at a glance

The infographic below is the whole rulebook. The sections after it explain the reasoning, because rules you can derive are rules you remember.

boxing-decision-map

The mental model is short: a value class stays unboxed exactly as long as the compiler can see its concrete type. The moment the value flows through something typed as Any, T, an interface, or a nullable slot that cannot hold a sentinel, the concrete type is gone and a real object is required.

3. Generics: erasure forces a wrapper

On the JVM, a type parameter erases to Object. A raw long cannot be an Object, so the compiler boxes.

val raw = longArrayOf(1_001, 1_002, 1_003)

val ids: List<UserId> = raw.map(::UserId)   // one UserId object per element
val byId: Map<UserId, String> = ids.associateWith { it.label }
Enter fullscreen mode Exit fullscreen mode

Everything built on a type parameter behaves the same way. The common offenders are:

  • List<UserId>, Set<UserId>, and Map<UserId, V> (keys and values).
  • Pair<UserId, X> and Triple.
  • Flow<UserId>, StateFlow<UserId>, and SharedFlow<UserId>. Each emission allocates.
  • Result<UserId>. Result is itself a value class over Any?, so it does not add a second wrapper, but the UserId inside is stored as an Object and is therefore boxed.
  • Array<UserId> and vararg ids: UserId. Both are arrays of wrapper objects, not arrays of long.

A subtle one is inline functions. Inlining map removes the lambda allocation, but it cannot change what the destination List<UserId> stores. The list's element type is still a generic parameter.

The cache trap people expect, and why it does not save you

You may remember that Long.valueOf caches small values between -128 and 127, so boxing a Long is sometimes free. Value classes do not benefit from this. box-impl constructs a fresh UserId every time, regardless of the number inside. A List<UserId> therefore costs one object per element even for ids like 1, 2 and 3.

The picture below shows why this matters beyond allocation counts: the list holds references to scattered objects, while a primitive array is one dense block the CPU can stream through.

memory-shapes

4. Nullability: the underlying type decides

This is the rule that surprises experienced engineers, because UserId? looks innocent.

nullability-rules

The logic is about spare representations:

  • If the underlying type is a non-null reference type (such as String), the compiler can encode "absent" as the null reference. Slug? costs nothing.
  • If the underlying type is a primitive, there is no spare long value that means "absent". The compiler must use an object reference that can be null, so RowId? boxes.
  • If the underlying type is already nullable, null is taken, so the nullable wrapper needs a real object.
@JvmInline value class RowId(val raw: Long)
@JvmInline value class Slug(val raw: String)

fun find(id: RowId?): String? = id?.let { "row-${it.raw}" }   // boxes when id is non-null
fun open(slug: Slug?): String? = slug?.raw                   // no allocation
Enter fullscreen mode Exit fullscreen mode

Failure mode: nullable IDs in hot data classes

A very common shape is data class Comment(val id: CommentId, val parentId: CommentId?). If CommentId wraps a Long, every comment with a parent allocates a wrapper for parentId when it is read through the nullable slot. Across a thread of a thousand replies, that is a thousand objects you did not write.

Two defensible fixes:

// Option A: encode "no parent" in the domain, not in the type system.
@JvmInline
value class CommentId(val raw: Long) {
    val isNone: Boolean get() = raw == NONE
    companion object { val None = CommentId(NONE); private const val NONE = -1L }
}
data class Comment(val id: CommentId, val parentId: CommentId = CommentId.None)

// Option B: keep a primitive in storage and expose the typed view at the edge.
data class CommentRow(val id: Long, val parentId: Long?)  // note: Long? is itself boxed, so this only helps where parentId is usually absent
Enter fullscreen mode Exit fullscreen mode

Option A is honest about the cost trade-off: you give up the compiler-enforced null and take on a sentinel convention. Use it only where a profile shows the allocation matters, and keep the sentinel private to the type so it cannot leak.

5. Interfaces and supertypes

A value class may implement interfaces. It may not extend classes. Calling a member on a known UserId is a static call and stays unboxed. Treating it as the interface type boxes.

interface Labeled { val label: String }

@JvmInline
value class UserId(val raw: Long) : Labeled {
    override val label: String get() = "user-$raw"
}

fun show(l: Labeled) = println(l.label)

fun demo() {
    val id = UserId(7)
    id.label            // static call on the raw long: no allocation
    show(id)            // boxes: the callee needs a real Labeled object
    val any: Any = id   // boxes
}
Enter fullscreen mode Exit fullscreen mode

Failure mode: Comparable and sorting

Making an ID comparable feels natural:

@JvmInline
value class UserId(val raw: Long) : Comparable<UserId> {
    override fun compareTo(other: UserId): Int = raw.compareTo(other.raw)
}

data class User(val id: UserId)

fun sortUsers(users: List<User>): List<User> = users.sortedBy { it.id }
Enter fullscreen mode Exit fullscreen mode

sortedBy is declared with R : Comparable<R> and delegates to a comparator built from your selector. That comparator runs the selector on both operands of every comparison, and each result is handed over as a Comparable, so each call boxes. Sorting n elements performs on the order of n log n comparisons, which means on the order of n log n wrapper allocations, not one per element. The same applies to maxByOrNull, compareBy, and sortedWith(compareBy { ... }).

The tempting fix is to select the raw property:

users.sortedBy { it.id.raw }   // swaps a UserId box for a java.lang.Long box
Enter fullscreen mode Exit fullscreen mode

That is not free. R is still a type parameter, so the Long is boxed instead (cheaper only for values in the small cache range). To avoid boxing entirely, compare the primitives in a plain comparator:

fun sortUsersFast(users: List<User>): List<User> =
    users.sortedWith { a, b -> a.id.raw.compareTo(b.id.raw) }   // no selector, no generic R
Enter fullscreen mode Exit fullscreen mode

You keep type safety in signatures and fields, and drop to the primitive only inside the comparison.

Failure mode: logging varargs

Loggers take vararg Any?, which is a generic-like boundary:

fun logLoaded(id: UserId) {
    Timber.d("loaded %s", id)      // vararg Any?: boxes id
    Timber.d("loaded ${id.raw}")   // reads the raw Long directly: no wrapper
    Timber.d("loaded $id")         // usually lowered to toString-impl; verify in your bytecode
}
Enter fullscreen mode Exit fullscreen mode

How a template containing a value class is lowered can vary with the Kotlin version and the string-concatenation strategy of your target, so do not assume the last line is free. Check for box-impl in the bytecode, or use ${id.raw}, which is guaranteed to stay primitive. Debug logging in a tight loop is a surprisingly common source of boxing. Prefer primitive templates, and guard the call so release builds skip the work entirely.

6. Lambdas and Compose state

Function types are generic interfaces. (UserId) -> Unit is a Function1<UserId, Unit>, and invoke takes an Object, so calling it through the interface boxes the argument.

Jetpack Compose is full of value classes (Dp, Color, IntOffset, TextUnit) and the same rules apply to them. Passing a Dp to Modifier.padding(...) is free. Holding one in generic state is not:

// Boxes a Dp every time the value changes, because State<T> is generic.
@Composable
fun BoxedWidth() {
    var width by remember { mutableStateOf(48.dp) }
    Box(Modifier.width(width))
}
Enter fullscreen mode Exit fullscreen mode

The idiomatic remedy is to store the primitive and wrap at the point of use:

@Composable
fun PrimitiveWidth() {
    var widthDp by remember { mutableFloatStateOf(48f) }   // primitive-specialized state
    Box(Modifier.width(widthDp.dp))                         // wrap at the edge, no box
}
Enter fullscreen mode Exit fullscreen mode

The same principle explains why Compose offers mutableIntStateOf, mutableLongStateOf, and mutableFloatStateOf: state that changes every frame should not allocate per write. Any animation that drives a State<Dp> deserves a look under the profiler for the same reason.

7. Proving it: bytecode, benchmark, profiler

Claims about allocation are cheap. Evidence is cheap too, if you know where to look. Use three layers, from fastest to most realistic.

investigation-loop

Layer 1: read the bytecode

Search the decompiled output for box-impl. A call site in your hot method is a confirmed allocation, no tooling required. Calls to unbox-impl mark the reverse trip and usually sit next to it. If you only see constructor-impl and *-impl statics, the value stayed raw.

Layer 2: isolate with a microbenchmark

Jetpack Microbenchmark reports an allocation count per iteration, which turns a vague suspicion into a number. Keep the experiment tiny so the signal is unambiguous:

@RunWith(AndroidJUnit4::class)
class ValueClassBoxingBenchmark {

    @get:Rule val benchmarkRule = BenchmarkRule()

    private val raw = LongArray(10_000) { it + 1_000L }
    @Volatile private var sink = 0L

    @Test fun listOfValueClass() = benchmarkRule.measureRepeated {
        val ids = ArrayList<UserId>(raw.size)
        for (r in raw) ids.add(UserId(r))     // box-impl per element
        var acc = 0L
        for (id in ids) acc += id.raw
        sink = acc
    }

    @Test fun primitiveArray() = benchmarkRule.measureRepeated {
        val copy = raw.copyOf()               // one array, no wrapper objects
        var acc = 0L
        for (r in copy) acc += r
        sink = acc
    }
}
Enter fullscreen mode Exit fullscreen mode

What you should expect, derived from the bytecode rather than from a particular device:

expected-allocations

Read the chart as an order-of-magnitude model: roughly one object per element for anything generic, and a handful of objects total for anything primitive-backed. For the listOfValueClass benchmark above, the 10,003 breaks down as one ArrayList, one backing Object[] (the list is presized), 10,000 UserId boxes, and one iterator from the for (id in ids) loop. Array<UserId> comes to 10,001 because an array loop allocates no iterator. An un-sized ArrayList() would add resize arrays on top. Your reported number will differ by a few allocations because of runtime internals, and that is fine. What you are looking for is the gap between N and 1.

A note on List<Long>: it appears in the chart because teams often assume it is free. Values outside the small cache range allocate too, so migrating from List<Long> to List<UserId> is neutral on allocation. It is not an improvement, and it is not a regression. Only a primitive-backed structure changes the cost.

Layer 3: confirm in the Android Studio Profiler

The benchmark tells you that a path allocates. The profiler tells you what it allocates and from where, inside your real app.

  1. Run a debuggable build on a physical device. Java/Kotlin allocation tracking needs a debuggable app; a profileable build suits timing and system traces but not this task. Debuggable builds skip some optimizations, so use the profiler for where and what, and let the release-like benchmark confirm the cost survives optimization. An emulator tells you about the emulator, so prefer hardware.
  2. Open the Profiler and choose the Java/Kotlin allocation tracking task. Older Studio versions expose the same thing as Record Java/Kotlin allocations in the Memory Profiler.
  3. Start recording, perform the scenario for a few seconds (scroll the feed, open the screen, trigger the flow), then stop.
  4. Group by class and search for your value class name. Each instance listed is a box-impl call that survived to the allocator.
  5. Sort by allocation count and open the call stack for the top entries. The stack points at the generic or nullable boundary that forced the box.

Two practical details. Allocation tracking adds overhead, so absolute timings from a tracked run are not meaningful. Use it for counts and stacks, then confirm the speed-up with a benchmark. And before a fix, take a note of the instance count for your type; after the fix, re-record and compare. The “before” number is what makes the change reviewable.

One honest caveat about runtime optimization. ART’s optimizing compiler can sometimes remove an allocation that never escapes a method, and R8 can inline small functions so a box and unbox pair disappears. That is exactly why you measure on a release-like build rather than reasoning from source alone. It is also why you should not design around the hope that the runtime will clean up: values that go into a collection, a flow, or a callback escape, and those are the cases that cost you.

8. Designing around it

Once you can see the boxing, the fix is rarely “stop using value classes”. It is “choose where the type lives”.

Rule 1: type the boundary, keep the interior primitive

Public function signatures and data model fields are where type safety pays for itself, and they stay unboxed. Collections of those values are where the cost accumulates, so give hot paths a primitive-backed container:

// UserId is the value class declared in Section 1.
@JvmInline
value class UserIdList(private val raw: LongArray) {
    val size: Int get() = raw.size
    operator fun get(index: Int): UserId = UserId(raw[index])   // wraps on read, caller usually unwraps immediately
    inline fun forEachId(action: (UserId) -> Unit) {
        for (i in 0 until size) action(UserId(raw[i]))           // inlined: no Function1, no box
    }

    companion object {
        fun of(vararg ids: Long) = UserIdList(ids)
    }
}
Enter fullscreen mode Exit fullscreen mode

forEachId is inline, so the lambda does not become a Function1 and the UserId stays a primitive inside the loop. UserIdList is itself a value class over a LongArray, so passing it around is free. The only boxing risk left is if a caller stores the result of get in a generic slot.

Rule 2: never use a value class as a nullable primitive substitute in hot structs

If a field is optional and appears in thousands of rows, prefer a documented sentinel inside the type (Section 4, Option A), or a separate boolean flag, over a nullable wrapper.

Rule 3: select the primitive in comparators and lookups

For sorting, prefer sortedWith { a, b -> a.id.raw.compareTo(b.id.raw) }, which compares primitives with no boxing. groupBy { it.id.raw } and associateBy { it.id.raw } still box the Long key in Map<Long, V>, but the cost is at least predictable. For truly hot lookups on large sets, a primitive-keyed structure such as androidx.collection.LongSparseArray or LongObjectMap avoids per-key boxing entirely.

Rule 4: do not box on the way to a logger

Use string templates, and gate debug logging so it vanishes from release builds.

9. Other failure modes that surface alongside boxing

Boxing is the headline, but the same compiler machinery produces neighbouring problems. These are worth a smoke test whenever you introduce a value class:

  • Mangled names break Java and reflection callers. load-<hash> is not a name you can call from Java without @JvmName, and reflection-based tools see the mangled form.
  • Serialization libraries differ in support. kotlinx.serialization handles single-property value classes by inlining them. Reflection-based libraries and older adapters may serialize the wrapper as an object or fail. Test a round trip through your real JSON and database layers.
  • Annotation processors read Java stubs. Generated code from kapt or KSP-based tools may see the mangled or unboxed signature. Check the generated sources, not just the build result.
  • Mocking. Stubbing functions that return or accept value classes has historically been fragile in mocking libraries. Confirm behaviour on the exact version you use, and prefer fakes for value-heavy interfaces.
  • Identity. === on a value class is meaningless. Equality is by value, which is usually what you want, but do not rely on boxed instances being shared.

Recent Kotlin releases have also been adding opt-in tooling for exposing boxed variants to Java callers. If interop is your main pain, check the current release notes rather than building workarounds from older blog posts, this one included.

10. A checklist before you merge

  • Does any value class appear as a type argument? That is a box per element. Is it on a hot path?
  • Is any value class nullable over a primitive? Prefer a sentinel or a flag in hot data.
  • Does any value class implement an interface that is used as the parameter type? That is a box per call.
  • Are you passing value classes to varargs, loggers, or Comparable-bound functions? Log or compare the raw property instead, and note that selecting a Long into a generic sortedBy boxes the Long, so use sortedWith.
  • Is a value class living inside State<T>, Flow<T>, or StateFlow<T>? Store a primitive and wrap at the edge.
  • Have you opened the bytecode and searched for box-impl, and compared profiler instance counts before and after?

🔚 Closing thought

Value classes are one of the best features Kotlin has given Android developers, and none of this argues against using them. The takeaway is narrower: the zero-cost guarantee holds inside a function and stops at the first generic, nullable, or interface boundary. Learn to spot those boundaries, give your hot paths primitive-backed containers, and let measurement, not memory, decide whether a given boundary matters. A single box-impl in a cold path is free. A thousand of them in a scroll handler is a frame you will never get back.

📘 Master Your Next Technical Interview

Since Java is the foundation of Android development, mastering DSA is essential. I highly recommend “Mastering Data Structures & Algorithms in Java”. It’s a focused roadmap covering 100+ coding challenges to help you ace your technical rounds.

Top comments (0)