Recall & Review
beginner
What is a smart cast in Kotlin?
A smart cast is when Kotlin automatically converts a variable to a more specific type after checking its type with conditions like
if or when, so you don't need to cast it manually.Click to reveal answer
beginner
How does Kotlin use smart casts inside an
if statement?Inside an
if block, if you check a variable's type (e.g., if (x is String)), Kotlin automatically treats x as that type inside the block without needing a manual cast.Click to reveal answer
intermediate
Explain smart casts with a
when expression.When you use
when to check a variable's type, Kotlin smart casts the variable to the matched type inside each branch, so you can use it directly as that type.Click to reveal answer
intermediate
Why can't Kotlin smart cast a variable if it is mutable (var) and can change?
If a variable is mutable (
var) and can be changed elsewhere, Kotlin can't guarantee its type stays the same, so it won't smart cast it to avoid errors.Click to reveal answer
beginner
Show a simple Kotlin example using smart casts in an
if statement.fun printLength(obj: Any) {
if (obj is String) {
// obj is smart cast to String here
println(obj.length)
} else {
println("Not a string")
}
}
Click to reveal answer
What does Kotlin do after you check
if (x is String) inside the if block?✗ Incorrect
Kotlin smart casts x to String inside the if block after the type check.
Can Kotlin smart cast a
var variable inside an if statement?✗ Incorrect
Kotlin won't smart cast mutable variables if they can be changed elsewhere.
In a
when expression, how does Kotlin handle smart casts?✗ Incorrect
Kotlin smart casts the variable to the matched type inside each when branch.
Which of these is a reason Kotlin might NOT smart cast a variable?
✗ Incorrect
If the variable is mutable and can change, Kotlin avoids smart casting to prevent errors.
What is the benefit of smart casts in Kotlin?
✗ Incorrect
Smart casts let you use variables as their checked type without extra casting code.
Explain how Kotlin smart casts work inside an if statement with a type check.
Think about how Kotlin treats the variable after confirming its type.
You got /3 concepts.
Describe why Kotlin might not smart cast a mutable variable and how this affects your code.
Consider what happens if the variable can change after the check.
You got /3 concepts.