What is Reified Type in Kotlin: Simple Explanation and Example
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.
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
}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
inlinefunctions. - They let you check or use the actual type without passing a
Classobject. - Only works with
inlinefunctions because of how Kotlin compiles code. - Useful for type checks, casts, and creating instances of generic types.