Smart Cast (Kotlin)
A smart cast is when the Kotlin compiler automatically casts a value to a more specific type after you've checked it, so you don't have to cast manually inside that scope.
Kotlin
After if (x is String) or a null check if (x != null), the compiler knows x's type in that branch and lets you use it as that type directly — no explicit (x as String) needed. This is the smart cast, and it works in if, when, and after early returns.
Smart casts require the compiler to guarantee the value can't change between the check and the use. That's why they apply to val and local variables but not to mutable properties (var) that other code could change, especially open or custom-getter properties — in those cases capture the value in a local val first.
Smart casts pair beautifully with when (is ...) over sealed classes and with null-safety checks, removing most manual casting from idiomatic Kotlin code.
Syntax
if (obj is String) { println(obj.length) } // obj used as StringExamples
Kotlin
fun describe(x: Any): String {
if (x is String) return "text of length ${x.length}"
return "other"
}
println(describe("hello"))
println(describe(42))Output:
text of length 5
other