Skip to content

Reified

Devrath edited this page Feb 11, 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.**

Clone this wiki locally