Skip to the workspace
Pebellslearn by building
Variables and Data Types  ›  Capstone Project

Type Checks and Casts

Type Checks & Casts 15 minThe is operator checks a value's type and can enable a smart cast when the compiler knows the value is stable. An incompatible as cast throws; as? returns null instead.

kotlin / Type Checks and Casts

Explore each scene at your own pace.

01 · The rule

The rule

Type Checks and Casts

The is operator checks a value's type and can enable a smart cast when the compiler knows the value is stable. An incompatible as cast throws; as? returns null instead.

Narrow a value using a type check and compare safe and unsafe casts.

Sometimes a value arrives whose exact type you do not know: a receipt line that might be a drink name or a quantity, stored as Any. Kotlin lets you ask "what are you?" and then, in the same breath, use the value as that type.

The rule

is asks and smart-casts; as insists and may crash; as? shrugs null.

is and !is check a type and give a Boolean. The magic is smart casting: once Kotlin has seen the check succeed, it treats the value as that type automatically.

val item: Any = "latte"

if (item is String) {
    println(item.uppercase())   // LATTE — no manual cast needed
}
if (item !is Int) {
    println("not a quantity")
}

Smart casts work when the compiler can be sure the value did not change between the check and the use, for example a local val.

as is an unsafe cast. It tells the compiler "trust me". If you are wrong, the program throws ClassCastException:

val qty: Any = 3
val name = qty as String        // crashes: an Int is not a String

as? is the safe cast. It gives the value on success and null on failure, so the result type is nullable:

val name: String? = qty as? String   // null, no crash

A cast never converts a value. It only changes how the compiler views an object that already is that type. val n: Any = 3; n as Long throws, because 3 is an Int. To change a number's type, use toLong().

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.