Junior — Middle
Can you explain what 'reified' means in the context of Kotlin and how it is used?
sobes.tech AI
Answer from AI
In Kotlin, the term "reified" is used in the context of generic functions with the inline modifier inline. Usually, in Kotlin, due to type erasure, information about generic types is not available at runtime. However, if a function is declared as inline and the type parameter is marked as reified, the compiler retains information about the specific type, which can then be used inside the function.
This allows, for example, type checks or creating instances of type T directly, which is usually not possible with regular generics.
Example of usage:
inline fun <reified T> isInstance(value: Any): Boolean {
return value is T
}
fun main() {
println(isInstance<String>("test")) // true
println(isInstance<Int>("test")) // false
}
Here, reified allows the use of the is operator with type T, which is normally unavailable due to type erasure.