Reification of the Erased

Ravi Ranjan     2020-07-02 10:07:21    


Reification of the Erased

provide type safety and help you avoid explicit type casts. Generics extend the type system to allow a type or method to operate on objects of various types while providing compile-time type safety.

On the other hand, generics can be limiting when you need to access type info in a generic function, and the compiler tells you the info doesn’t exist! This missing type info is a result of how generics are implemented in the JVM (hint: type erasure, which we’ll discuss later). As a workaround, you can access the deleted generic type by passing the class of the generic type as a parameter of the function. This isn’t too bad, but as you know from other posts in the Kotlin Vocabulary series, Kotlin hates boilerplate code and aims to help you write less code! Kotlin addresses this problem with a unique keyword, reified, that lets you access the type info from within a generic function. If you are familiar with how generics work, you might be asking how this is even possible.