Language: Kotlin · Versions: Kotlin 2.1.0 (JVM target 21)
The problem
I defined an @JvmInline value class Outcome<out T>(val rawValue: Any?) (similar to kotlin.Result<T>) or a simpler @JvmInline value class Box<T>(val value: T) to wrap results without heap allocation. However, when Box<T> is instantiated as Box<Box<String?>?>, the JVM representation erases the outer Box to its underlying carrier unless it has to disambiguate null (outer is null) from Box(null) (outer is present, inner is null)—at which point the JVM compiler boxes the inner Box on the heap, and generic reflection / is checks behave surprisingly!
Minimal example
@JvmInline
value class Box<T>(val value: T)
fun <T> unwrapOrDefault(box: Box<T>?, default: T): T =
if (box == null) default else box.value
fun main() {
val a: Box<String?>? = null
val b: Box<String?>? = Box(null)
println("a == null: ${a == null}") // true
println("b == null: ${b == null}") // false, yet b.value == null!
println("unwrap(a): ${unwrapOrDefault(a, "fallback")}")
println("unwrap(b): ${unwrapOrDefault(b, "fallback")}")
}
Expected
Clear understanding of when @JvmInline value class is forced to heap-box on the JVM (specifically nullable value classes wrapping nullable types Box<String?>?) and why kotlin.Result<T> uses an internal Failure wrapper instead of nesting Result<Result<T>>.
What happens instead
When Box<T> wraps a nullable type T = String? and the variable itself is nullable (Box<String?>?), both a = null and b = Box(null) would map to null if unboxed! Therefore, the Kotlin JVM compiler must heap-allocate a Box wrapper object for b = Box(null) whenever a nullable value class wraps a nullable or generic type parameter, silently defeating the zero-allocation guarantee on hot paths.
How can you design a zero-allocation @JvmInline value class in Kotlin 2.1 that represents an optional/sentinel state without triggering heap boxing on nullable generic paths?
Your example prints the correct results. The boxing is by design, and it is what keeps Box(null) distinct from null. I'm going from the Kotlin inline-classes docs and the value-classes KEEP, and I haven't compiled this.
What happens in your example
Box<T>(val value: T) erases to Object on the JVM. Box<String?>? can't use the unboxed representation, because null would then mean both "no box" and "box holding null". So the compiler passes a real Box object there, and b = Box(null) allocates one. That is why b == null is false and unwrapOrDefault(b, ...) returns null rather than "fallback". It is the right answer, not a bug.
The docs say a value class is also boxed in other positions:
- when it is used as a generic argument, such as
List<Box<T>> - when it is typed as an interface or
Any - when it is nullable over a nullable or generic carrier, as in your case
A nullable value class over a non-null reference type stays unboxed, with null as the absent state. That is the one case that doesn't allocate.
Zero-allocation optional: don't make the wrapper nullable
Put the absent state inside the carrier as a sentinel, and never write Opt<T>?:
private object Absent
@JvmInline
value class Opt<out T> @PublishedApi internal constructor(@PublishedApi internal val raw: Any?) {
val isPresent: Boolean get() = raw !== Absent
@Suppress("UNCHECKED_CAST")
fun getOrElse(default: @UnsafeVariance T): T = if (raw === Absent) default else raw as T
companion object {
fun <T> of(v: T): Opt<T> = Opt(v)
fun <T> none(): Opt<T> = Opt(Absent)
}
}
This is the same idea as kotlin.Result. Its Failure wrapper is a sentinel-like carrier value, so Result never needs to be nullable to express failure. Opt<Opt<String?>> also works, but the inner Opt is boxed because it sits in a generic argument position. That box is a distinct non-Absent object, so the states stay distinguishable. You pay one allocation only in the nested case.
Caveats
Opt<T>?,List<Opt<T>>andOptpassed asAnywill box. Keep the type non-null and concrete on hot paths.- For primitives, use a specialised carrier such as
value class OptInt(val raw: Long). That needs a reserved sentinel value likeLong.MIN_VALUE, which is a real trade-off. - The unchecked cast is safe only if the constructor stays internal.
- To settle whether a given call site allocates, check the bytecode with
javap -cforOpt.box-implcalls, or use a JMH allocation profiler (-prof gc). I'm not asserting that every site is unboxed.