Smart casts let Kotlin automatically convert a variable to a specific type after you check it. This makes your code simpler and safer.
Smart casts in when and if in Kotlin
if (variable is Type) { // variable is smart cast to Type here } when (variable) { is Type1 -> { // variable is smart cast to Type1 here } is Type2 -> { // variable is smart cast to Type2 here } else -> { // variable is not any of the above types } }
Kotlin automatically casts the variable inside the if or when block after checking its type.
You don't need to use explicit casts like variable as Type inside these blocks.
obj is checked if it is a String. Inside the if block, Kotlin lets you use obj as a String directly.val obj: Any = "Hello" if (obj is String) { println(obj.length) // smart cast to String }
obj. Each branch smart casts obj to the checked type.val obj: Any = 123 when (obj) { is Int -> println(obj + 1) // smart cast to Int is String -> println(obj.length) else -> println("Unknown type") }
This program uses a when expression with smart casts to handle different types of obj. It prints a description based on the type.
fun describe(obj: Any): String { return when (obj) { is Int -> "Integer: ${obj + 1}" is String -> "String of length ${obj.length}" else -> "Unknown type" } } fun main() { println(describe(10)) println(describe("Kotlin")) println(describe(3.14)) }
Smart casts only work if the variable cannot change between the check and usage (like val or local variables).
If the variable is mutable or a property with a custom getter, Kotlin may not smart cast it.
Smart casts let you use variables as a specific type after checking their type.
They work automatically inside if and when blocks.
This feature makes your Kotlin code cleaner and safer.
Practice
if or when block?Solution
Step 1: Understand smart cast purpose
Smart casts let Kotlin automatically treat a variable as a more specific type after you check its type.Step 2: Apply to if/when blocks
Insideiforwhen, Kotlin knows the variable's type and lets you use it without manual casting.Final Answer:
Automatically treats a variable as a specific type after a type check -> Option CQuick Check:
Smart cast = automatic type use after check [OK]
- Thinking manual cast is always needed
- Assuming smart casts disable type checks
- Believing variables convert to string automatically
when expression for variable obj?Solution
Step 1: Check correct when syntax
Thewhenexpression requires parentheses around the variable:when (obj).Step 2: Use type check correctly
The correct type check isis Stringwithout repeating variable name inside the block.Final Answer:
when (obj) { is String -> println(obj.length) else -> println("Not a string") } -> Option DQuick Check:
Correct when syntax uses parentheses andis[OK]
- Omitting parentheses around variable
- Using variable name inside when branches
- Using type name without 'is' keyword
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)Solution
Step 1: Analyze each call
Fortest("Hello"),objis String, so prints length 5.
Fortest(5),objis Int, so prints 5 + 1 = 6.
Fortest(3.14), no matching type, prints "Unknown".Step 2: Confirm output lines
Outputs are:
5
6
UnknownFinal Answer:
5 6 Unknown -> Option BQuick Check:
Smart cast uses type to choose output [OK]
- Confusing string length with string itself
- Adding 1 to string instead of int
- Expecting default else to print number
fun check(obj: Any) {
if (obj is String) {
println(obj.length)
} else if (obj is Int) {
println(obj + 1)
} else {
println(obj.length)
}
}Solution
Step 1: Review else block usage
In the else block,objcan be any type, but code tries to accessobj.lengthwhich is invalid for non-String types.Step 2: Understand smart cast limits
Smart casts only apply after type checks. Here, no type check before accessinglengthin else block causes error.Final Answer:
Trying to access length on obj in else block without type check -> Option AQuick Check:
Access property only after type check [OK]
- Assuming else block has smart cast automatically
- Confusing else if with when
- Thinking smart casts fail inside if blocks
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"
}
}
}Solution
Step 1: Check smart cast usage in when
Thewhenexpression smart castsitemtoStringorIntautomatically after type check.Step 2: Confirm lambda and map usage
Inside the lambda, smart casts work normally, so accessingitem.lengthanditemis valid without explicit casts.Final Answer:
Correct as is, smart casts allow using item.length and item directly -> Option AQuick Check:
Smart casts work inside lambdas and when [OK]
- Adding unnecessary explicit casts
- Thinking smart casts don't work in lambdas
- Replacing when with if-else unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
