liveBook · Manning

ClassCastException

As explained in Kotlin in Action, 2E

ClassCastException is a JVM runtime exception thrown when a value is used as an incompatible type.

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

How Kotlin in Action, 2E covers it

How deep it goes
Traces a cast from compiler warning through successful runtime check to failure during numeric summation.
Examples
Uses printSum with integer lists, integer sets, and string lists to contrast successful output and two exception paths.
What it assumes
Assumes familiarity with Kotlin collections, generics, casts, and runtime type checks.
What you can do after
Diagnose/debug unchecked generic casts by distinguishing failures at the cast boundary from failures during value use.
How it connects
Connects ClassCastException with generics, type casts, type checks, type erasure, and inline functions.

Also explained in

Compare how 2 books explain ClassCastException →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.