...

/

Reified Type Parameters

Reified Type Parameters

Why reified type parameters are needed

When using generics in Java we sometimes get into smelly situations where we have to pass Class<T> parameters to functions. This becomes necessary when the specific parametric type is needed in a generic function but the type details are lost due to Java’s type erasure. Kotlin removes this smell with reified type parameters.

To get a clear understanding of reification, we’ll first explore some verbose and unpleasant code where we pass the class details as a parameter to a function, and then we’ll refactor the code to use type reification.

Suppose we have a base class Book and a couple of derived classes, like so:

// reifiedtype.kts
abstract class Book(val name: String)
class Fiction(name: String) : Book(name)
class NonFiction(name: String) : Book(name)
...