Bird
0
0

Why does Kotlin not apply smart casts to a var variable inside a when expression?

hard📝 Conceptual Q10 of 15
Kotlin - Control Flow as Expressions
Why does Kotlin not apply smart casts to a var variable inside a when expression?
ABecause <code>when</code> does not support smart casts.
BBecause smart casts only work with <code>val</code> declared inside functions.
CBecause <code>var</code> variables are always nullable.
DBecause the variable can be reassigned, making type unsafe.
Step-by-Step Solution
Solution:
  1. Step 1: Recall smart cast requirements

    Smart casts require variables to be stable and not reassigned.
  2. Step 2: Understand mutability impact

    var variables can be reassigned, so Kotlin cannot guarantee type safety for smart casts.
  3. Final Answer:

    Because the variable can be reassigned, making type unsafe. -> Option D
  4. Quick Check:

    Mutability prevents smart cast [OK]
Quick Trick: Mutable vars prevent smart casts due to reassignment risk [OK]
Common Mistakes:
MISTAKES
  • Thinking smart casts depend on declaration location
  • Assuming all vars are nullable
  • Believing when disables smart casts

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes