Reified generics
Reified generics in Kotlin address a limitation of the JVM called type erasure. Type erasure means that generic type information is lost at runtime. This restriction prevents you from performing certain operations, like type checking, with generic types.
For instance, the following code will not compile:
fun <T> printIfSameType(a: Number) {
if (a is T) { // Error: Cannot check for instance of erased type: T
println(a)
}
}
A common workaround is to pass the class as an argument:
fun <T : Number> printIfSameType(clazz: KClass<T>, a: Number) {
if (clazz.isInstance(a)) {
println("Yes")
} else {
println("No")
}
}
You can see this approach in the Intent
class of the Android codebase, for example.
This approach, requiring the explicit passing of the class type and the use of isInstance()
instead of the is
operator, can be streamlined using reified generics:
inline...