Part 13 / Topic 5 of 7
Type erasure and reified
At runtime, the JVM does not remember a generic type's type argument -- a List<String> and a
List<Double> are both simply "a List" once the program is running. This is type erasure,
and it's why it is T inside an ordinary generic function is a compile error: there is no T
left to check against at runtime.
fun <T> List<Any>.oldFilterByType(): List<T> {
// return filter { it is T }.map { it as T } // does NOT compile:
// "Cannot check for instance of erased type: T"
@Suppress("UNCHECKED_CAST")
return this as List<T> // compiles, but it's a lie: no real check happens
}
The workaround is inline + reified. An inline function's body is copied into every call
site at compile time instead of being called normally; reified tells the compiler to also
substitute the real type argument into that copy -- so T genuinely exists, as the real type,
for the duration of that one inlined call. reified is only legal on an inline function's
type parameter, for exactly this reason.
inline fun <reified T> List<Any>.filterByType(): List<T> =
filter { it is T }.map { it as T }
val mixed: List<Any> = listOf("Rice", 199.0, "Dal", 45.0, "Oil", 320)
val strings = mixed.filterByType<String>()
val doubles = mixed.filterByType<Double>()
val ints = mixed.filterByType<Int>()
println("Strings: $strings")
println("Doubles: $doubles")
println("Ints: $ints")
val unsafe: List<String> = mixed.oldFilterByType()
println("Unsafe cast claims ${unsafe.size} strings, but the list still has mixed types inside")
Strings: [Rice, Dal, Oil]
Doubles: [199.0, 45.0]
Ints: [320]
Unsafe cast claims 6 strings, but the list still has mixed types inside
unsafe.size prints 6, not 3 -- oldFilterByType never actually checked anything, it just
relabelled the same six-element list as a List<String> and hoped nobody looks too closely.
That's the real danger of an unchecked cast: it compiles, it "works" in the sense that it doesn't
crash immediately, and it silently hands back wrong data instead.
🔍 Going deeper:
reifiedis whyinline fun <reified T> List<Any>.only()was mentioned back in the DESIGN-NOTES as what makes coroutine-adjacent generic helpers (and plenty of standard-library functions, likefilterIsInstance<T>()) possible at all. Part 15 (Kotlin internals) coversinline/noinline/crossinlinein depth; this part only needed enough ofinlineto explain whyreifiedis legal here.
Full program: examples/05_type_erasure_and_reified.kt.
Done here? The practice set for Part 13 — including the solutions — is on the part page.