-
Notifications
You must be signed in to change notification settings - Fork 22
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
![Screenshot 2024-02-11 at 9 16 07β―AM](https://private-user-images.githubusercontent.com/1456191/303897154-1ae1f5c2-5696-4c01-bce4-aa57333b1727.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjQ2MTUwNjcsIm5iZiI6MTcyNDYxNDc2NywicGF0aCI6Ii8xNDU2MTkxLzMwMzg5NzE1NC0xYWUxZjVjMi01Njk2LTRjMDEtYmNlNC1hYTU3MzMzYjE3MjcucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI0MDgyNSUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNDA4MjVUMTkzOTI3WiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9NDNmOTI3ZjM4M2NmMDI1NzJmYzFlMWVjOTQ3NDc0ODkzZTE5Y2RlOWQzYjQ5YjY4NzgxMDA1ZmM3NjUxYTRkMCZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QmYWN0b3JfaWQ9MCZrZXlfaWQ9MCZyZXBvX2lkPTAifQ.XjcBFfKfTzEIS5WkDSJvd3CkvzAWw0_hVeOHlSxfGSI)
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