ClassCastException is a JVM runtime exception thrown when a value is used as an incompatible type. Generic type arguments are unavailable during some runtime casts, so an unchecked cast can succeed before failing later. section 11.2.1
A generic cast that fails later
fun printSum(c: Collection<*>) { val intList = c as? List<Int> ?: throw IllegalArgumentException("List is expected") println(intList.sum()) } printSum(listOf("a", "b", "c")) // ClassCastException: String cannot be cast to Number The cast cannot verify Int at runtime because the type argument is not known. It therefore succeeds, but sum later attempts to use String values as Number values. A set fails earlier with IllegalArgumentException because it is not a List. section 11.2.1
Listing 11.5 Using a type cast with a generic type
fun printSum(c: Collection<*>) {
val intList = c as? List<Int> #1
?: throw IllegalArgumentException("List is expected")
println(intList.sum())
}
Inspect the compact printSum example that demonstrates the unchecked generic cast. section 11.2.1

