Since the inline function is copied, we can get rid of one of the major JVM limitations–type erasure. After all, inside the function, we know exactly what type we're getting.
Let's look at the following example. You would like to create a generic function, which will receive a number but will print it only if it's of the same type as the function.
You can try writing something like this:
fun <T> printIfSameType(a: Number) {
if (a is T) { // <== Error
println(a)
}
}
But this code won't compile with an error as follows:
Cannot check for instance of erased type: T
What we usually do in Java, in this case, is pass the class as an argument:
fun <T: Number> printIfSameType(clazz: KClass<T>, a: Number) {
if (clazz.isInstance(a) ) {
println(a)
}
}
We can check this code by running the following two lines...