-
Notifications
You must be signed in to change notification settings - Fork 23
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 means that whenever a code is compiled every
generic param
is erased and replaced withspecific 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
code(With Solution)
inline fun <reified T : Any> newInstance() {
val clazz = T::class.java
}
- 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 asinline
, As it enables the substitution of the inline keyword with code
- 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
withreified
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