0
0
KotlinConceptBeginner · 3 min read

What is Reified Type in Kotlin: Simple Explanation and Example

In Kotlin, a reified type allows you to access the actual type arguments of a generic function at runtime. Normally, generic types are erased during compilation, but marking a type as reified inside an inline function keeps the type information available for use.
⚙️

How It Works

Imagine you have a box labeled "T" but you don't know what's inside until you open it. Normally, Kotlin removes the label "T" when the program runs, so you can't check the type inside the box. This is called type erasure.

However, if you mark the generic type as reified inside an inline function, Kotlin keeps the label visible at runtime. This means you can check or use the actual type inside the function, like checking if the box contains apples or oranges.

This works only with inline functions because the function's code is copied to the call site, allowing the compiler to replace the generic type with the real type directly.

💻

Example

This example shows how to use a reified type to check the type of an object at runtime inside a generic function.

kotlin
inline fun <reified T> isOfType(value: Any): Boolean {
    return value is T
}

fun main() {
    println(isOfType<String>("Hello"))  // true
    println(isOfType<Int>(123))          // true
    println(isOfType<Double>(123))       // false
}
Output
true true false
🎯

When to Use

Use reified types when you need to access the actual type inside a generic function at runtime. This is helpful for tasks like type checking, casting, or creating instances of a generic type.

For example, when you want to write a function that filters a list by type or creates objects based on the type parameter, reified types let you do this without passing the class explicitly.

Key Points

  • Reified types keep generic type info at runtime inside inline functions.
  • They let you check or use the actual type without passing a Class object.
  • Only works with inline functions because of how Kotlin compiles code.
  • Useful for type checks, casts, and creating instances of generic types.

Key Takeaways

Reified types allow access to generic type information at runtime in Kotlin.
They require the function to be marked as inline to work properly.
Use reified types for type checks, casts, and instance creation without extra parameters.
Without reified, generic types are erased and unavailable at runtime.
Reified types simplify generic programming by avoiding manual class passing.