Bird
0
0

In Kotlin, which condition allows smart casting inside a when expression?

easy📝 Conceptual Q2 of 15
Kotlin - Control Flow as Expressions
In Kotlin, which condition allows smart casting inside a when expression?
AWhen the variable is declared inside a function only.
BWhen the variable is declared as <code>var</code> and changed inside <code>when</code>.
CWhen the variable is a primitive type only.
DWhen the variable is immutable or not modified after the check.
Step-by-Step Solution
Solution:
  1. Step 1: Identify smart cast requirements

    Kotlin smart casts work only if the variable is immutable or not changed after the type check.
  2. Step 2: Understand mutability impact

    If the variable is mutable and changed, Kotlin cannot guarantee type safety, so smart cast is not applied.
  3. Final Answer:

    When the variable is immutable or not modified after the check. -> Option D
  4. Quick Check:

    Smart casts require immutability or no modification [OK]
Quick Trick: Smart casts need stable (unchanged) variables [OK]
Common Mistakes:
MISTAKES
  • Assuming smart casts work with mutable variables
  • Believing smart casts depend on variable type only
  • Thinking smart casts require variable declaration location

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes