0Pricing
Kotlin Academy · Lesson

Smart Casts

Auto-cast after checks.

What Are Smart Casts

After you check a value's type, Kotlin remembers that fact. Inside the checked block, it treats the value as the narrowed type automatically.

This feature is called a smart cast, and it removes manual casting.

Smart Cast After is

Once an is check passes, you can use the value as that type without writing a cast.

The compiler inserts it for you.

fun describe(x: Any) {
    if (x is String) {
        println(x.length) // x is smart-cast to String
    }
}

fun main() {
    describe("hello")
}

All lessons in this course

  1. when as Expression
  2. Smart Casts
  3. is and as Operators
  4. Exhaustive when
← Back to Kotlin Academy