tutorial, no_image, kotlin,

Kotlin - no_image

Upendra Upendra Follow Jan 23, 2025 · 4 mins read
Kotlin - no_image
Share this

reified keyword

The keyword reified enables access to information about type at runtime in inline functions. This allows for more flexibility and type-safe operations at runtime and improves the code’s readability.

In Java, generic types suffer from type erasure, which means that the information about actual types used in the generic class is not available at runtime. This limitation restricts the ability to perform certain operations like checking the type of a generic parameter at runtime, leading to the need for explicit casting and potential runtime errors.1

Kotlin introduces the reified modifier to address the limitations imposed by type erasure. When a type parameter is marked as reified, it allows us to access the actual type at runtime within inline functions. This effectively provides the ability to perform type checks, type casts, and create instances of the type parameter at runtime.

By using reified type parameters, we can write more concise and type-safe code within inline functions, eliminating the need for explicit casts and improving the overall reliability of our code.2

Let’s take a look at an example:

fun <T> TreeNode.findParentOfType(clazz: Class<T>): T? {
    var p = parent
    while (p != null && !clazz.isInstance(p)) {
        p = p.parent
    }
    @Suppress("UNCHECKED_CAST")
    return p as T?
}

Here, you walk up a tree and use reflection to check whether a node has a certain type. It’s all fine, but the call site is not very pretty:

treeNode.findParentOfType(MyTreeNode::class.java)

A better solution would be to simply pass a type to this function. You can call it as follows:

treeNode.findParentOfType<MyTreeNode>()

To enable this, inline functions support reified type parameters, so you can write something like this:

inline fun <reified T> TreeNode.findParentOfType(): T? {
    var p = parent
    while (p != null && p !is T) {
        p = p.parent
    }
    return p as T?
}

The code above qualifies the type parameter with the reified modifier to make it accessible inside the function, almost as if it were a normal class. Since the function is inlined, no reflection is needed and normal operators like !is and as are now available for you to use. Also, you can call the function as shown above: myTree.findParentOfType<MyTreeNodeType>().3

Real word example is navigation in Android. In Java, when we call startActivity, we need to specify the destination class as a parameter. In Kotlin, we can simplify it by adding the type to the function:

inline fun <reified T : Activity> Activity.startActivity() {
    startActivity(Intent(this, T::class.java))
}

Navigating to an Activity is now as easy as this:4

startActivity<DetailActivity>()

Benefits of Reified Type Parameters

The use of reified type parameters brings several benefits to Kotlin developers:

  • Type-safe Operations. Reified type parameters enable type-safe operations within inline functions, eliminating the need for explicit casts and reducing the likelihood of runtime errors;
  • Improved Code Readability. By leveraging reified type parameters, the code becomes more concise and readable as the type information is available at runtime, simplifying conditional logic and type-based operations;
  • Enhanced API Design. APIs utilizing reified type parameters can offer more intuitive and streamlined interfaces, as the type information can be leveraged directly within the function body.

Limitations and Considerations

While reified type parameters provide significant advantages, there are some limitations and considerations to keep in mind:

  • Only for Inline Functions. Reified type parameters can only be used within inline functions, which restricts their applicability to certain contexts;
  • Memory Overhead. Using reified type parameters within inline functions may lead to increased memory overhead, as the bytecode of the inline function is duplicated at each call site;
  • Reflective Operations. While reified type parameters allow for type checks and casts, they do not support general reflective operations, such as obtaining class references or working with reflection APIs.

Links

Understanding Kotlin’s Reified Type Parameters

Inline functions

Reified Types in Kotlin: how to use the type within a function (KAD 14)

Further reading

Kotlin Generics: Reified Type Parameter with Inline Function

How Reified Type makes Kotlin so much better

Introduction to Kotlin Generics: Reified Generic Parameters

Next questions

What do you know about inline keyword?

credit goes to @swayangjit
Join Newsletter
Get the latest news right in your inbox. We never spam!
Upendra
Written by Upendra Follow
Hi, I am Upendra, the author in Human and machine languages,I don't know to how 3 liner bio works so just Connect with me on social sites you will get to know me better.