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.if or when block?if or when, Kotlin knows the variable's type and lets you use it without manual casting.when expression for variable obj?when expression requires parentheses around the variable: when (obj).is String without repeating variable name inside the block.is [OK]fun test(obj: Any) {
when (obj) {
is String -> println(obj.length)
is Int -> println(obj + 1)
else -> println("Unknown")
}
}
test("Hello")
test(5)
test(3.14)test("Hello"), obj is String, so prints length 5.test(5), obj is Int, so prints 5 + 1 = 6.test(3.14), no matching type, prints "Unknown".fun check(obj: Any) {
if (obj is String) {
println(obj.length)
} else if (obj is Int) {
println(obj + 1)
} else {
println(obj.length)
}
}obj can be any type, but code tries to access obj.length which is invalid for non-String types.length in else block causes error.Any objects, write a Kotlin function using when with smart casts to return a list of strings describing each element's type and value. What is the correct implementation?fun describeList(items: List<Any>): List<String> {
return items.map { item ->
when (item) {
is String -> "String of length ${'$'}{item.length}"
is Int -> "Int with value ${'$'}item"
else -> "Unknown type"
}
}
}when expression smart casts item to String or Int automatically after type check.item.length and item is valid without explicit casts.Pass the test and this pattern moves unknown