Sobes.tech
Junior — Middle

In what cases can the reified modifier be used inside inline functions in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, the reified modifier is used only inside inline functions and allows access to the type parameter at runtime, which is usually impossible due to type erasure.

Using reified is justified when you need to:

  • Check the type using is or !is.
  • Create an instance of the type via reflection.
  • Obtain the class of type T::class or T::class.java.

Example:

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

Here, reified allows using T::class.java inside the function, which is impossible without inline and reified.