Kotlin reified Keyword
inline and reified.Reified types
In Kotlin, reified is a special type parameter that is usually used together with inline functions.
Under the JVM specification, generic type parameters are generally erased at runtime. This is related to Java’s type erasure. In other words, information about the actual type of a generic type is not available at runtime. However, Kotlin’s reified keyword lets you work around this limitation. That is, it makes it possible to refer to generic function type information even at runtime.
The reified keyword makes the generic type parameter actually known inside an inline function. Therefore, runtime information about the generic type can be used inside the inline function.
For example, the following is a simple example that uses the reified keyword to determine the actual generic type and perform a runtime type check for that type.
inline fun <reified T> exampleFunction(item: T) {
if (item is String) {
println("It's a String!")
} else {
println("It's not a String!")
}
}
fun main() {
exampleFunction("Hello") // Output: It's a String!
exampleFunction(5) // Output: It's not a String!
}
In the example above, exampleFunction has the generic type T and is marked with the reified keyword. Now runtime information about T can be used inside the function. Therefore, runtime type checks such as item is String can be performed.
The reified keyword is mainly used with inline functions that need type information, and it is useful when type information must be used at runtime.