typestar

Smart casts in Kotlin

Passing an is-check narrows the type for the rest of the branch.

fun label(reading: Any): String {
    // A passed is-check narrows the type for the rest of the branch.
    if (reading is Double) return "temp ${reading * 1.8 + 32} F"
    return when (reading) {
        is Int -> "wind $reading km/h"
        is String -> "note: ${reading.trim()}"
        else -> "unreadable"
    }
}

fun main() {
    println(label(-3.5))
    println(label(38))
    println(label("  bridge icy  "))
    // as? yields null instead of throwing on a bad cast.
    val maybe: Int? = ("17" as Any) as? Int
    println(maybe)
}

How it works

  1. After if (reading is Double), reading is a Double — no cast to write.
  2. when branches on is Int and is String narrow the same way.
  3. as? returns null on a failed cast where as would throw.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
477
Tokens
118
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 109 seconds.

Type this snippet

Step 2 of 3 in Null safety, step 17 of 27 in Language basics.

← Previous Next →