0
0
Kotlinprogramming~5 mins

Smart casts in when and if in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThrows an error if you use x as String
BAutomatically treats x as String without manual cast
CRequires you to cast x manually
DChanges the type of x permanently
Can Kotlin smart cast a var variable inside an if statement?
AOnly if the variable is null
BYes, always
CNo, if the variable can change
DOnly if the variable is a primitive type
In a when expression, how does Kotlin handle smart casts?
AIt smart casts the variable to the matched type in each branch
BIt never smart casts in when expressions
CIt requires manual casting in each branch
DIt only smart casts if the variable is a String
Which of these is a reason Kotlin might NOT smart cast a variable?
AThe variable is immutable (val)
BThe variable is a local variable
CThe variable is checked with is operator
DThe variable is mutable (var) and can be changed
What is the benefit of smart casts in Kotlin?
AYou write less code by avoiding manual casts
BIt makes the program slower
CIt requires more manual type checks
DIt disables type safety
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.