Kotlin

Smart Casts

admin by @admin ADMIN
Jun 13, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
After a successful `is` check (or null check), the compiler "smart-casts" the variable to the narrower type in that scope. No explicit cast needed.
Kotlin
Raw
fun describe(x: Any): String {
    if (x is String) {
        // x is now smart-cast to String here — can call String methods directly
        return "string of length ${x.length}"
    }
    if (x is List<*>) {
        return "list of ${x.size} items"
    }
    return "something else"
}

fun greet(name: String?) {
    if (name == null) return
    // Below this line `name` is smart-cast to non-null String
    println("Hello, ${name.uppercase()}")
}

// In when:
fun area(shape: Any): Double = when (shape) {
    is Pair<*, *> -> {
        // Smart cast only works if the type info is preserved (here we'd
        // need explicit casts since generics are erased at runtime).
        0.0
    }
    is List<*>    -> shape.size.toDouble()         // smart cast → List<*>
    else          -> 0.0
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.