0Pricing
Kotlin Academy · Lesson

Type Erasure and reified Type Parameters

Use reified with inline functions to access type information at runtime.

What Is Type Erasure?

At runtime, JVM erases generic type arguments. List<String> and List<Int> are both just List. This limits runtime type operations on generics.

fun main() {
    val strings: List<String> = listOf("a", "b")
    val ints: List<Int> = listOf(1, 2)
    println(strings.javaClass == ints.javaClass) // true: both ArrayList
    println(strings is List<*>)  // OK with star
    // println(strings is List<String>) // warning: unchecked cast
}

The Problem: Cannot Check Erased Types

You cannot use is with a specific generic type argument because the type info is gone at runtime.

fun checkType(obj: Any) {
    // This works:
    if (obj is List<*>) println("It's a list of something")
    // This doesn't compile cleanly:
    // if (obj is List<String>) println("It's a list of strings") // unchecked
}
fun main() {
    checkType(listOf("hello"))
    checkType(42)
}

All lessons in this course

  1. Generic Functions and Type Constraints with where
  2. Declaration-Site Variance: in and out
  3. Star Projection and When to Use *
  4. Type Erasure and reified Type Parameters
← Back to Kotlin Academy