June 2018
Intermediate to advanced
310 pages
6h 32m
English
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 ...
Read now
Unlock full access