Search⌘ K
AI Features

Generic Type Erasure and Constraints

Explore Kotlin's generic type erasure, understanding why type arguments are lost during compilation and how that impacts type checks. Learn to apply generic constraints for subtype safety, use multiple constraints with where clauses, and handle star projections for flexible type usage in Kotlin.

Type erasure

Generic types were added to Java for developers’ convenience, but they were never built into the JVM platform. All type arguments are lost when we compile Kotlin to JVM bytecode. Under the hood, this means that List<String> becomes List, and emptyList<Double> becomes emptyList. The process of losing type arguments is known as type erasure. Due to this process, type parameters have some limitations compared to regular types.

  • We cannot use them for is checks.

  • We cannot reference them.

  • We cannot use them as reified type arguments.

Kotlin 1.5
import kotlin.reflect.typeOf
fun <T> example(a: Any) {
val check = a is T // ERROR
val ref = T::class // ERROR
val type = typeOf<T>() // ERROR
}

However, Kotlin can overcome these limitations thanks to the use of inline functions with reified type arguments.

import kotlin.reflect.typeOf
inline fun <reified T> example(a: Any) {
val check = a is T
val ref = T::class
val type = typeOf<T>()
}
Using inline functions with reified type arguments
...