Compiling your code gives the following warning:
Unchecked cast: Any? to List<Int>
This literally means that the cast will not throw an exception in all cases. If you choose to ignore this warning, you should be prepared for this behaviour to happen.
Now as to why this actually runs fine, keep in mind that generic types are erased at runtime. This means that a List<String>
or a List<Int>
is actually just a raw List
at runtime, the information about the element type is lost.
The point of the generics is mostly to help when compiling the code: the compiler prevents you from adding elements of the wrong type to the list, and it helps you when you read elements from the list by giving you a value with the proper type (no cast required).
Casts, however, operate at runtime. They check the runtime type of an object against a given type. The type List<Int>
that you cast to is a generic type, and the compiler warns you because at runtime it will only see the raw interface List
.
More concretely, somePair.second as List<Int>
compares the runtime type of somePair.second
(which is ArrayList
here) with the raw List
interface - and that is a match, so no exception.