Reified parameters— What, Why and How?

We may have read about reified type parameters with inline functions when we start learning Kotlin. Every time it left with me with a question of What, Why and How?

The purpose of this article is to answer these questions:

WHAT ?

Let’s start with meaning of reified(derived from reify). Reify means to keep the existence or to consider something as real.If we talk in context of parameters it could mean that Type definition of parameter should exist.

WHY?

Why do we need reified, we always know the type of parameter passed. No, this statement is not completely true. Let’s take a look at Type Erasure to understand this completely:

List<T> is a generic interface and we can pass on ArrayList<String> and hence T= String. But actually, this information is not available at runtime and image below shows the error faced.

Finding type of List

The compiler throws away this understanding of T as String and this is known as “Type Erasure”.

HOW?

How can we keep this information at runtime?

  1. We would qualify the type with reified keyword.
  2. Make the function inline.

Type erasure is not done and compiler modifies the generated bytecode to use the corresponding class directly. As the function is inlined, the code is copied to call site and compiler directly replaces T with actual type being passed.

Therefore calls like myVar is T becomes myVar is String.
This works!!

Thanks for taking out time to read this :)