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)

Here’s a list that includes different kinds of books:

// reifiedtype.kts
val books: List<Book> = listOf(
  Fiction("Moby Dick"), NonFiction("Learn to Code"), Fiction("LOTR"))

The list contains a mixture of Fiction and NonFiction instances in the List<Book>. Now, suppose we want to find the first instance of a particular type, either a Fiction or a NonFiction from the list. We may write a function like this in Kotlin, much like how we’d write it in Java:

Get hands-on with 1200+ tech skills courses.