Concept Flow - Smart casts in when and if
Start
Check type with if/when
Smart cast variable
Use variable as casted type
End
The program checks a variable's type using if or when, then automatically treats it as that type inside the block.
fun demo(x: Any) { if (x is String) { println(x.length) } else { println("Not a string") } }
| Step | Condition | Condition Result | Smart Cast Applied | Action | Output |
|---|---|---|---|---|---|
| 1 | x is String | True | x as String | Print x.length | 5 |
| 2 | x is String | False | No cast | Print "Not a string" | Not a string |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| x | Any ("Hello") | Smart cast to String | No cast | Any/String depending on branch |
Smart casts let Kotlin treat a variable as a specific type after checking with if or when.
Syntax: if (x is Type) { use x as Type }
No explicit cast needed inside the block.
If condition false, no cast happens.
Smart casts improve safety and readability.