inline, crossinline and reified

inline, crossinline and reified in Kotlin: --- In a machine shop, every part that moves through the floor carries a job traveler: a paper that rides along with…


The Analogy: The Machine Shop and the Job Traveler

In a machine shop, every part that moves through the floor carries a job traveler: a paper that rides along with the work, listing each operation the part must undergo. When an operation needs a sub-task done, the shop has two ways to arrange it. It can send the part off to a separate department, which keeps its own traveler and its own bench -- that is an ordinary function call, with the handling, the queue and the second sheet of paper that a handoff involves. Or the operation can copy the sub-task's steps directly onto the part's own traveler and perform them right there at the bench, no handoff and no second sheet. Copying the steps in place is what inline does: the function's body, and the bodies of any lambdas passed to it, are stamped into the call site at compile time rather than called as separate objects.

The shop's blank travelers have a box marked MATERIAL. For filing convenience, when a traveler goes into the general rack the specific entry -- "brass rod, 12mm" -- is rubbed down to the generic word STOCK, because the rack does not care what the stock was. That erasure is exactly what the JVM does to type parameters: by the time the code runs, the specific type argument is gone and only a generic shape remains. But here is the consequence of copying steps in place. When an operation's steps are stamped directly onto this part's traveler, the specific material is written right there in the copied text, not filed away generically, so any downstream station can still read "brass" and act on it. That is reified: because the function was inlined, its type parameter survives into the runtime code, and you can ask is T or T::class where an ordinary generic could not.

Some copied steps are not done at your bench at all; they are handed to a runner who carries them out in the yard. You are allowed to copy such steps onto your traveler, but you are forbidden from writing "and if this fails, abandon the whole job and clock off" among them, because the runner is out in the yard and cannot reach back to halt your bench work. That restriction is crossinline: a lambda that is still inlined but is barred from a non-local return, because it will be invoked from another context that cannot perform one.

The failure mode is the foreman who copies a fifty-step operation onto every one of a thousand travelers instead of routing the parts to a department that does it once. Each traveler swells into a booklet, the filing cabinets overflow, and the shop drowns in paper -- which is what happens when you inline a large function called from many sites and the compiled code bloats at every call. And a station that was promised it could read the material off the traveler will find only STOCK if the traveler came from the general rack rather than being stamped in place -- which is what happens when you try to use a reified type outside the inline context that gave it life.


Syntax or Core Structure

inline fun <reified T> Any?.orNull(): T? = this as? T

inline fun twice(action: () -> Unit) {
    action()
    action()
}

fun main() {
    val a: Any = "signal"
    println("as String: " + a.orNull<String>())
    println("as Int: " + a.orNull<Int>())

    var beeps = 0
    twice { beeps += 1 }
    println("beeps: " + beeps)
}

orNull is inline with a reified T, so the safe cast this as? T -- which needs the real runtime type -- is legal; an ordinary generic function could not write it. twice is inline and takes a lambda, so the body beeps += 1 is stamped into the call site twice with no function object allocated. The type argument in a.orNull<String>() is supplied at the call, and that is what reification makes available inside.

Output:

as String: signal
as Int: null
beeps: 2

a really holds "signal", so orNull<String>() casts successfully and returns it, while orNull<Int>() fails the safe cast and returns null. twice runs its lambda two times, leaving beeps at 2.


Technical Depth: What Inlining Buys, and What Reified Cannot Reach

The four modifiers and what each does

Inlining is the mechanism; the other three modifiers adjust it. The table fixes each one. Read the middle column as what it attaches to and the right column as its effect.

ModifierAttaches toEffect
inlinea functionstamps the body and its lambdas into each call site
noinlinea lambda parameterkeeps that lambda a real object, not stamped in
crossinlinea lambda parameterstamped in but barred from a non-local return
reifieda type parametermakes the type readable at runtime, inline only

Two facts follow from "stamped into the call site." Because the lambda body is copied in rather than boxed into a function object, a lambda passed to an inline function allocates nothing and may contain a non-local return. And because the type argument is copied in with the body, a reified parameter is present at runtime, which is the only way is T, as T and T::class become legal for a type parameter on the JVM.

Reified type checks, which erasure normally forbids

Outside an inline function, a type parameter is erased: fun <T> Any.isA() = this is T does not compile, because at runtime there is no T to test against. Make the function inline with reified T and the check is legal, because the concrete type is stamped in at each call.

inline fun <reified T> Any.isA(): Boolean = this is T

fun main() {
    val x: Any = "hello"
    println("String? " + x.isA<String>())
    println("Int? " + x.isA<Int>())
    val y: Any = 42
    println("Number? " + y.isA<Number>())
}

Output:

String? true
Int? false
Number? true

x is really a String, so isA<String>() is true and isA<Int>() is false. y is an Int, which is a Number, so isA<Number>() is true. Each call stamped its own concrete type into the is check.

Non-local return through inline, and where crossinline bans it

A lambda passed to an inline function may return from the enclosing function -- the non-local return -- because it was stamped in and shares the caller's frame. A crossinline lambda is still inlined but is forbidden this power, because it will be invoked from another context, such as inside a stored lambda or an object, that cannot unwind the caller.

inline fun run2(block: () -> Unit) {
    block()
    block()
}

fun findFirstOdd(xs: List<Int>): Int {
    xs.forEach { if (it % 2 == 1) return it }
    return -1
}

fun main() {
    var sum = 0
    run2 { sum += 5 }
    println("sum: " + sum)
    println("first odd: " + findFirstOdd(listOf(2, 4, 7, 9)))
}

Output:

sum: 10
first odd: 7

run2 stamps its lambda in twice, so sum reaches 10. In findFirstOdd, the lambda passed to the inline forEach uses a bare return it, a non-local return that exits the whole function on the first odd value, 7. Had forEach required a crossinline lambda, that return it would not compile.


Real World Example: Counting a Mixed List by Type

The program holds a list of mixed Any values and reports how many are of each type, using a single reified helper. pick<T>() keeps every element that is a T, which is only expressible because the function is inline and T is reified. The report counts Int, String and Double values, and a final line demonstrates the one thing reification cannot do.

inline fun <reified T> List<Any>.pick(): List<T> {
    val out = ArrayList<T>()
    for (e in this) if (e is T) out.add(e)
    return out
}

const val W_TYPE = 8
const val W_COUNT = 7
const val W_FIRST = 8

fun row(type: String, count: String, first: String): String =
    type.padStart(W_TYPE) + count.padStart(W_COUNT) + first.padStart(W_FIRST)

fun main() {
    val items: List<Any> = listOf(3, "york", 1.5, 8, "leeds", 2.5, "hull", 4)
    val ints = items.pick<Int>()
    val strings = items.pick<String>()
    val doubles = items.pick<Double>()

    val ruleWidth = W_TYPE + W_COUNT + W_FIRST
    println(row("TYPE", "COUNT", "FIRST"))
    println("-".repeat(ruleWidth))
    println(row("Int", ints.size.toString(), ints.first().toString()))
    println(row("String", strings.size.toString(), strings.first()))
    println(row("Double", doubles.size.toString(), doubles.first().toString()))
    println("-".repeat(ruleWidth))
    val known = ints.size + strings.size + doubles.size
    println(row("TOTAL", known.toString(), "--"))

    println("items: " + items.size)
    println("sum of ints: " + ints.sum())
    println("string chars: " + strings.sumOf { it.length })
    println("covers all: " + (known == items.size))

    val nested: List<Any> = listOf(listOf(1, 2), listOf("a", "b"))
    val stringLists = nested.pick<List<String>>()
    println("picked List<String>: " + stringLists.size + " of " + nested.size)
}

Output:

    TYPE  COUNT   FIRST
-----------------------
     Int      3       3
  String      3    york
  Double      2     1.5
-----------------------
   TOTAL      8      --
items: 8
sum of ints: 15
string chars: 13
covers all: true
picked List<String>: 2 of 2

Trace the counts. The list holds eight values: the integers 3, 8 and 4, the strings york, leeds and hull, and the doubles 1.5 and 2.5. pick<Int>() keeps the three integers, whose first is 3 and whose sum is 15; pick<String>() keeps the three strings, whose first is york and whose lengths total 13; pick<Double>() keeps the two doubles, whose first is 1.5. The known total of 3 + 3 + 2 is 8, which equals items.size, so covers all is true -- a genuine check that would read false if the list held a value of some fourth type.

The pick function earns its keep only because it is inline with a reified T. The line if (e is T) would not compile in an ordinary generic function, since T would be erased and there would be nothing to test at runtime. Because pick is inlined, each call -- pick<Int>(), pick<String>(), pick<Double>() -- stamps its concrete type into the is check, so each correctly recognises its own elements.

The last line is the genuine design flaw, and it is inherent to reification rather than to sloppiness in this code. reified reifies only the immediate type argument, not the type arguments nested inside it. When pick<List<String>>() runs, the check e is T becomes e is List<String>, which the JVM can only test as e is List -- the element type String is still erased. So both entries of nested match, and the call reports 2 of 2 even though one of the two lists is a List<Int>. A caller who trusted pick<List<String>>() to return only string lists would silently receive an integer list too, with no cast error until an element was actually read as a String. Reification lifts one layer of erasure, never the layers beneath it. A narrower limit is the usual alignment one: padStart never truncates, so a type label longer than eight characters would push its row past the rule.


Common Mistakes

  1. Using is T, as T or T::class in a non-inline generic function. A plain type parameter is erased at runtime, so none of these compile. They become legal only when the function is inline and the parameter is reified, which stamps the concrete type into each call.
  1. Marking a large function inline. Inlining copies the whole body into every call site, so a big inline function called from many places multiplies the compiled code. Reserve inline for small functions, chiefly those taking lambda parameters.
  1. Trying to store or pass on an inlined lambda. An inlined lambda has no object to store; assigning it to a variable or handing it to another function is an error. The parameter must be marked noinline for that to be allowed.
  1. Attempting a non-local return from a crossinline lambda. crossinline exists precisely to forbid it, because the lambda runs in another context that cannot unwind the caller. A bare return there is a compile error, not a runtime surprise.
  1. Forgetting crossinline when a lambda is invoked from another context. If an inline function passes its lambda into a nested lambda, a stored closure, or an object, the compiler demands crossinline on that parameter and refuses to build until you add it.
  1. Expecting reified to reify nested type arguments. reified T recovers only the top-level type. A check on List<String> still tests only List, so a reified helper cannot tell List<String> from List<Int>; the element type remains erased.
  1. Inlining a plain function with no lambda parameters for speed. The JIT already inlines many small calls, and Kotlin's inline mainly pays for lambda parameters and reification. Inlining an ordinary function rarely helps and can enlarge the code for nothing.
  1. Referencing non-public declarations from a public inline function. Because the body is copied into callers, a public inline function may not touch private members -- the copied code would be reaching things it cannot see. The compiler rejects it with a visibility error.
  1. Expecting a reified type to come from a runtime value. A reified type is fixed by the static type argument at the call site, not by a Class object you obtained at runtime. If all you have is a runtime Class<*>, reification cannot help and you must pass and use that token explicitly.

Best Practices

  • Reserve inline for small functions that take lambda parameters, where it removes the lambda allocation and enables non-local returns -- the cases where it genuinely pays.
  • Use reified to avoid threading Class<T> tokens through your API; inline fun <reified T> lets the call site's type argument do the work.
  • Mark a lambda parameter noinline whenever you must store it, return it, or pass it to a non-inline function.
  • Use crossinline for a lambda that will be invoked from another execution context, and make clear to callers that a non-local return is unavailable there.
  • Keep inline function bodies small and free of non-public references, since every caller receives a copy of that body.
  • Do not inline large functions or plain functions without lambdas; the code-size cost outweighs any benefit, and the JIT handles ordinary small calls already.
  • Remember that reification lifts only the outermost layer of erasure, and design APIs so they never depend on distinguishing nested generic types at runtime.
  • Measure before inlining for performance rather than assuming; the real, reliable wins of inline are lambda elimination and reified, not shaving ordinary call overhead.

Practice Exercises

  1. Write inline fun <reified T> List<Any>.firstOfType(): T? that returns the first element which is a T, or null. Test it on a mixed list for Int and for String, and explain why the function must be inline for is T to compile.
  1. Write a non-inline fun <T> check(x: Any): Boolean that tries to return x is T and observe that it does not compile. Fix it by making the function inline with reified T, then verify check<String>("hi") and check<Int>("hi").
  1. Write an inline function with a lambda parameter and perform a non-local return from that lambda at a call site. Then add crossinline to the parameter and confirm the non-local return no longer compiles, explaining why.
  1. Demonstrate reification's nested-erasure limit: build a list holding both a List<Int> and a List<String>, call a reified pick<List<String>>() over it, and show that both lists are matched. State precisely which type reification recovered and which it did not.