Type erasure
Type erasure was introduced into JVM to make JVM bytecode backward compatible with versions that predate the introduction of generics. On the Android platform, both Kotlin and Java are compiled to JVM bytecode, so they both are vulnerable to type erasure.
Type erasure is the process of removing a type argument from a generic type so that the generic type loses some of its type information (type argument) at runtime:
package test class Box<T> val intBox = Box<Int>() val stringBox = Box<String>() println(intBox.javaClass) // prints: test.Box println(stringBox.javaClass) // prints: test.Box
The compiler can distinguish between these types and guarantee type safety. However, during compilation, the parameterized types Box<Int>
and Box<String>
are translated by the compiler to a Box
(raw type). The generated Java bytecode does not contain any information related to type arguments, so we can't distinguish betweengeneric types at...