Reified Type Parameters
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:
| abstract class Book(val name: String) |
| class Fiction(name: String) : Book(name) ... |
Get Programming Kotlin now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.