How to Use Reified with Inline Function in Kotlin
In Kotlin, you use
reified with inline functions to access the actual type arguments at runtime, which is normally erased. Mark the function as inline and the type parameter as reified to use the type inside the function body.Syntax
The syntax requires marking the function as inline and the type parameter as reified. This allows you to use the type parameter inside the function, for example, to check the type or create instances.
inline: tells the compiler to inline the function code at call sites.reified: keeps the type information available at runtime.T: the generic type parameter you want to access.
kotlin
inline fun <reified T> myFunction() {
println("Type is: ${T::class}")
}Example
This example shows how to use a reified type parameter to check the type of an object and cast it safely inside an inline function.
kotlin
inline fun <reified T> isInstance(value: Any): Boolean {
return value is T
}
fun main() {
val number = 42
val text = "Hello"
println(isInstance<Int>(number)) // true
println(isInstance<String>(number)) // false
println(isInstance<String>(text)) // true
}Output
true
false
true
Common Pitfalls
One common mistake is trying to use reified without marking the function as inline. This causes a compilation error because reified only works with inline functions.
Another pitfall is expecting to use reified in non-generic or non-inline contexts, which is not allowed.
kotlin
/* Wrong: reified without inline causes error */ // fun <reified T> wrongFunction() { } // Error /* Correct: inline with reified */ inline fun <reified T> correctFunction() { }
Quick Reference
| Keyword | Purpose |
|---|---|
| inline | Makes the function inline to allow reified type usage |
| reified | Keeps generic type info at runtime inside inline functions |
| T | Generic type parameter accessible at runtime |
Key Takeaways
Use
inline to enable reified type parameters in Kotlin functions.reified allows accessing the actual type inside the function body at runtime.You cannot use
reified without inline functions; it causes a compile error.Reified type parameters let you perform type checks and casts safely inside generic functions.