Skip to content

Reified

Devrath edited this page Feb 25, 2024 · 5 revisions

With reified generics we can avoid type-erasure that comes with java-generics

Type Erasure

  • Type erasure means that whenever a code is compiled every generic param is erased and replaced with specific object type.
  • So during the runtime we don't have any generic type arguments.
  • So JAVA byte code does not know generics.

code(With error)

fun <T : Any> newInstance(clazz:Class<T>) {
    val clazz = T::class.java
}

error

Screenshot 2024-02-11 at 9 16 07β€―AM

code(With Solution)

inline fun <reified T : Any> newInstance() {
    val clazz = T::class.java
}

Marking with reified keyword

  • When you mark your generic type with a reified keyword, You will be able to access it during the runtime.
  • When using the reified keyword, it is necessary to mark the function as inline, As it enables the substitution of the inline keyword with code

Summary

  • Problem: When we use generics in kotlin and try to cast a Type in a function, The Type erasure happens and the compiler throws an error
  • Solution: We can just mark the left of the type T with reified and make that generic function inline so that the code is substituted at compile time so the appropriate type would be available.
  • Usecase: When we use Gson to convert to JSON, Say this conversion function we make as generic so that it works with any class
Clone this wiki locally