-
Notifications
You must be signed in to change notification settings - Fork 24
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 means that whenever a code is compiled every
generic paramis 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
refied keyword, it is necessary to mark the function asinline, As it enables the substitution of inline keyword with code
