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.
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
ischecks.We cannot reference them.
We cannot use them as reified type arguments.
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>()}