Reading 2nd edition of Kotlin in Action.
There is an example with an unsafe cast to a generic List<T>
type with an Int
assumption for type argument:
fun printSum(c: Collection<*>) {
val intList = c as? List<Int> // If 'c' is a `List`, Int is not guaranteed because of type erasure
?: throw IllegalArgumentException("List is expected")
println(intList.sum())
}
The code compiles with a WARNing on unsafe cast and passing a list of strings:
printSum(listOf("a", "b", "c"))
will explode with java.lang.ClassCastException
:
Exception in thread “main” java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Number (java.lang.String and java.lang.Number are in module java.base of loader ‘bootstrap’)
The ClassCastException
is expected, but why the error message complains on a java.lang.Number
and not on an Int
/java.lang.Integer
?
There is not direct references to java.lang.Number
class in the code and the sum()
function called is an extension on Iterable<Int>
(not Iterable<Number>
).