Sobes.tech
Junior — Middle

How is the reified keyword used in Kotlin for working with types at runtime?

sobes.tech AI

Answer from AI

In Kotlin, the keyword reified is used together with inline functions to retain type information at runtime, which is usually impossible due to type erasure on the JVM.

When a function is declared as inline and the type parameter is marked as reified, the compiler inserts the specific type into the function body, allowing it to be used for operations that require reflection or type checking at runtime.

Example of usage:

inline fun <reified T> Gson.fromJson(json: String): T {
    return this.fromJson(json, T::class.java)
}

// Call
val user: User = gson.fromJson(jsonString)

Without reified, you would have to pass the class type explicitly, for example, fromJson(json, User::class.java). With reified, this becomes more convenient and safer.

Thus, reified allows working with types at runtime inside inline functions, bypassing JVM limitations on type erasure.