What is Type Erasure in Kotlin: Explanation and Example
type erasure means that generic type information is removed at runtime, so the program does not know the exact types used in generics. This happens because Kotlin runs on the JVM, which does not keep generic types after compilation.How It Works
Type erasure in Kotlin means that when you use generics, the specific type information is only available while the program is being compiled. After that, the JVM removes this information, so at runtime, the program only knows about the raw types without the details.
Think of it like a cookie cutter: during baking (compilation), you shape cookies with different patterns (types), but once baked (runtime), all cookies look the same shape without the pattern details. This is because the JVM does not keep track of the generic type details to keep things simple and compatible.
This means you cannot check or use the exact generic type inside your code at runtime, which can sometimes limit what you can do with generics.
Example
This example shows how Kotlin removes generic type information at runtime, making it impossible to check the exact generic type.
fun <T> printType(value: T) {
if (value is List<*>) {
println("It's a list")
} else {
println("Unknown type")
}
}
fun main() {
val list = listOf("a", "b", "c")
printType(list)
}When to Use
Understanding type erasure is important when working with generics in Kotlin, especially if you want to check or use the exact generic type at runtime. Since this is not possible directly, you might need to use workarounds like passing KClass or TypeToken to keep type info.
Use this knowledge when designing libraries or APIs that rely on generics and need to behave differently based on the type. It helps avoid bugs and unexpected behavior caused by missing type information at runtime.
Key Points
- Type erasure removes generic type info at runtime on the JVM.
- Kotlin generics work only at compile time for type safety.
- You cannot check generic types directly at runtime.
- Use type tokens or class references to keep type info if needed.