Generic Type Erasure and Constraints
Understand the concept of type erasure, constraints, and star projection in Kotlin's generics.
We'll cover the following...
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.
Press + to interact
import kotlin.reflect.typeOffun <T> example(a: Any) {val check = a is T // ERRORval ref = T::class // ERRORval type = typeOf<T>() // ERROR}
However, Kotlin can overcome these limitations thanks to the use of inline functions with reified type arguments.
import kotlin.reflect.typeOfinline fun <reified T> example(a: Any) {val check = a is Tval ref = T::classval type = typeOf<T>()}
Using inline functions with reified type arguments
...