Reified in Kotlin
Siddhant Mishra
Senior Android Developer at Teachmint | Kotlin and Java | DSA - 300+ on Leetcode | I read and write about Android and DSA
Today I will be writing about the type erasure in Java and Kotlin and its solution.
The concept of type erasure stems from the fact that for previous versions of Java there were no concept of Generics(popularly represented as <T> in classes's, functions's definitions), hence after introduction of newer Java versions and to keep resonance with the older versions they did not retain the datatype at runtime this is what we call type erasure.
And Kotlin also started to respect the type erasure to let developers use the old java libraries seamlessly.
Now for understaning what exactly type erasure is, check this below code -
In the above function I am trying to check the type of a variable, I am passing. The cache is that, the type checking is being done at the runtime where the type of something is compared with T, and at runtime, the JVM can not infer the type of the generic type(T) this is what exactly is type erasure and at the compile time itself it gives us the suggestion -
Now in the suggestion it tells us to change the function to inline(yes reified only works with inline function) and add the reified keyword before T(our generic data type).
Now the correct way to check the type looks something like this -
Now the function gives us correct answers, as it remembers the String and Boolean as the generic data types for the two method calls.
Follow me to read about such simplified concepts. Happy Coding
Software engineer | PHP | Laravel | jQuery | Javascript | React js | git | WordPress | Bootstrap | Tailwind | devops
8 个月Useful tips