Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 134 ยท Generics and Types

Type Erasure and reified

Why Kotlin cannot check 'is List<String>' at run time, what type erasure means on the JVM, and how inline functions with reified type parameters bring the type back.

Generics are a compile-time feature. When your program runs on the JVM, the type arguments are gone: a List<String> and a List<Int> are both just a List. This is called type erasure, and it explains a whole family of confusing Kotlin messages: "Cannot check for instance of erased type", "Unchecked cast", "Cannot use 'T' as reified type parameter".

The good news is that Kotlin has an elegant answer for the most common case. A function declared inline with a reified type parameter keeps its type argument alive, so you can write value is T, T::class and filterIsInstance<T>() as if generics had no limits. This lesson explains erasure with working code, shows what is and is not possible, and then teaches reified step by step, including its limits. It builds on Generics and Inline Functions.

What erasure means

When the compiler checks your code, it knows that names is a List<String> and will stop you from adding an Int. It then compiles the code to JVM bytecode, which has no way of saying "list of String" in a value; it keeps only the class List. The type argument existed to help the compiler and is thrown away. You can observe this directly:

Kotlin Two lists, one class at run time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both lists are exactly java.util.ArrayList at run time. The elements know their own classes (String, Int, Double), but the container does not remember what it was declared to hold. Erasure exists for compatibility: generics were added to the JVM world after millions of lines of code existed, and erasure let old and new code work together.

What you cannot do: is-checks on generic types

Because the type argument is not available when the program runs, the compiler cannot test it. Asking "is this a List<String>?" would require inspecting every element, which the language refuses to pretend it does:

Kotlin is List of String is not allowed (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler says error: cannot check for instance of erased type 'List<String>'. (Interesting detail: a reified type parameter, shown below, may be given List<String> and then checks only the List part.) The check you can make is is List<*>, which asks only about the class and uses the star projection from Generics:

Kotlin Checking the class and then the elements yourself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at the third line of output: an empty List<Int> is reported as "a list of strings", because all on an empty list is vacuously true. The run-time view of a list is only its contents, never its declared type. If you must know the element type of an empty container, you have to carry the information yourself (a Class or KClass parameter, which we meet below).

Unchecked casts

A cast to a generic type is allowed, but the compiler warns, because it can only check the class and not the arguments. This is the one place where erasure can make a program crash far from the actual mistake:

Kotlin An unchecked cast fails later, somewhere else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Without the @Suppress the compiler reports an "unchecked cast" warning on that line. The program does not fail at the cast, nor when asking for size. It fails when the first element is actually used as a String. Programmers call this heap pollution: a list that claims String but holds Int. Treat the warning as a real signal, and suppress it only in a small, well-commented place where you have other proof that the type is right.

Type parameters are erased in functions too

The same restriction applies to the T of a generic function. This tiny function looks reasonable, yet it cannot compile:

Kotlin is T on a plain type parameter (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The error is cannot check for instance of erased type 'T (of fun <T> isInstance)'. Inside isInstance there is no T; the JVM only sees Object. Kotlin's solution is to inline the function body into the caller, where the real type is known.

reified: bringing the type back

An inline function is not called at run time. The compiler copies its body into every place that calls it. At such a call site, the type argument is known (String in isInstance<String>("hello")), so the compiler can paste the real type into the copied body. Marking the type parameter reified asks the compiler to do exactly that:

Kotlin A working isInstance with reified

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Two small changes made it work: inline on the function and reified before T. In the compiled code, isInstance<String>("hello") has become "hello" is String. Note that reification restores the class, not nested type arguments. Even isInstance<List<String>>(listOf(1)) compiles here and prints true, because only the List part can be checked. Prefer the honest star form List<*> so nobody is misled.

T::class and T::class.java

Reified parameters give you the class object as well. This makes many APIs pleasant to call:

Kotlin Class names and a typed lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

filterIsInstance<String>() in the standard library is inline fun <reified R> Iterable<*>.filterIsInstance(): List<R>. Without reified, you would have to write filterIsInstance(String::class.java), which is what Java code must do. Notice typeName<List<String>>() prints just List: even a reified T::class knows the class but not its arguments.

T::class.java gives the Java Class object, which is what many Java libraries want. A typical utility in real projects looks like this:

Kotlin Creating a typed array and a default instance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Array<T> is a real run-time array of its element class, so creating one needs the real T; this only works because it is reified. Creating an instance by reflection (getDeclaredConstructor().newInstance()) is a Java technique that needs a no-argument constructor. Treat it as a last resort; passing a factory lambda () -> T is usually cleaner.

The limits of reified

Reified type parameters are powerful but narrow. Memorize these rules:

  1. Only on inline functions (and inline properties). A regular function or a class cannot have a reified parameter.
  2. A reified function can only be called with a known type. From another generic function with an ordinary T, the type is still erased.
  3. Public inline functions cannot touch non-public API, because their body is copied into other code. That is an inline restriction, covered in Inline Functions.
  4. Only the class is reified. T::class for List<String> is List.
  5. Java code cannot call a function with a reified parameter, because it has no inlining.

Rule 2 produces a classic error. Suppose you wrap the reified isInstance in a regular generic function:

Kotlin Passing an erased T to reified (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler answers error: cannot use 'T' as reified type parameter. Use a class instead. The fix is to make check inline and reified too:

Kotlin Making the wrapper inline and reified

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Reification spreads upward through the call chain until you reach a place where the type is known.

Alternatives when you cannot use reified

Sometimes the function cannot be inline (it is an interface method, it is large, it is called from Java). You then pass the class explicitly, as many older APIs do:

Kotlin Passing the class as a parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This is a very common design: an explicit KClass<T> (or Java Class<T>) parameter at the core, and a small inline reified wrapper on top for convenient calls. kotlin-reflect is not needed for isInstance or simpleName; see Reflection Overview for what needs the full library.

Libraries that need a full generic type at run time, such as a JSON mapper that must know List<User> and not just List, use a type token: a small anonymous subclass (object : TypeToken<List<User>>() {}) whose supertype keeps the argument in the class metadata. That is the only trick that survives erasure for nested arguments, and it is why you will see this odd syntax in Java and Kotlin code alike.

When to use reified

Use it when a generic function must test, filter, create or look up by type: filterIsInstance, getSystemService<T>()-style lookups, typed event buses, assertFailsWith<MyException>-like helpers, deserialization (parse<User>(text)). Avoid it for large functions called in many places (inlining copies the body everywhere), and do not use it just because T appears in a signature; most generic code needs no run-time type at all.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is type erasure?

    Type arguments exist only for the compiler. At run time, both lists are java.util.List (or ArrayList), with no memory of their declared element type.
  2. 2. Which check compiles in Kotlin?

    Only the star-projected form asks about the class alone. The other forms mention type arguments or an erased T, so the compiler reports 'cannot check for instance of erased type'.
  3. 3. What two keywords make value is T legal inside a generic function?

    The function must be inline, so its body is copied to the call site where the real type is known, and the type parameter must be marked reified.
  4. 4. What does typeName<List<String>>() print for inline fun <reified T> typeName() = T::class.simpleName?

    Reified gives you the class, not its type arguments. T::class for List<String> is List, and its simple name is List.
  5. 5. Why does the compiler warn about obj as List<String>?

    After erasure the cast checks the class only. A wrong element type shows up later as a ClassCastException when an element is used, so the cast is 'unchecked'.

Summary

  • On the JVM, generic type arguments are erased: List<String> and List<Int> are the same class when the program runs.
  • You cannot write is List<String> or is T; you can write is List<*>, and casts to generic types are unchecked (compiler warning) and may fail later.
  • An inline function with a reified type parameter gets the real type pasted in at each call site, so is T, T::class, T::class.java and Array<T> all work.
  • filterIsInstance<T>() is the standard example of a reified function.
  • Reified works only for inline functions, only restores the class (not nested arguments), and spreads upward: a regular generic caller cannot supply it.
  • When inlining is not possible, pass KClass<T> or Class<T> explicitly, often with a small reified wrapper on top.

Next: Generic Constraints