Introduction
In Java, we have a type erasure problem where the runtime will not be able to preserve the type of the generic type that was intended and that will result in many times we having to pass the name of the class like Class<clz> .. to provide the context information to perform the operations in generics.
Type Erasure
fun <T> getOnlyInts(list: List<Any>): MutableList<T> {
var result: MutableList<T> = mutableListOf()
for (item in list)
if (item is T) {
result.add(item)
}
return result
}
The above snippet of code illustrates the problem of type erasure where the type information for T is lost at runtime. this results in the type check failure in the line item is T
Since the type data is erased , the runtime cannot figure out if it is performing the right type check. Hence the compilation fails.
reiefied
In Kotlin, we have the reified types which helps us to preserve the type information that can help in preserving the type information when invoking this method call.
inline fun <reified T> getOnlyInts(list: List<Any>): MutableList<T> {
var result: MutableList<T> = mutableListOf()
for (item in list)
if (item is T) {
result.add(item)
}
return result
}
The constraint here is that the method should be both inline and should have the type as reified so that the Kotlin compiler can add the context for the type T based on the location where it is inlining and help us overcome the type erasure problem.
Below given is the full code that you can run and validate.
import java.math.BigDecimal
fun main() {
var lst = listOf<Any>(1, "Helo", BigDecimal(12.12312), 0.34f, 0.0, "end")
println(getOnlyInts<Number>(lst))
}
inline fun <reified T> getOnlyInts(list: List<Any>): MutableList<T> {
var result: MutableList<T> = mutableListOf()
for (item in list)
if (item is T) {
result.add(item)
}
return result
}
Comments
Post a Comment