Search⌘ K
AI Features

Reified Type Parameters

Explore how Kotlin's reified type parameters help overcome type erasure in generics, allowing safer and cleaner code without passing runtime class information. Understand how marking functions as inline lets you use parametric types for type checks and casts, enhancing code readability and safety.

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:

//
...