Bird
0
0

What is the behavior of Kotlin's smart cast when used inside an if statement that checks a variable's type?

easy📝 Conceptual Q1 of 15
Kotlin - Control Flow as Expressions
What is the behavior of Kotlin's smart cast when used inside an if statement that checks a variable's type?
AThe variable is automatically cast to the checked type within the <code>if</code> block.
BThe variable must be explicitly cast using <code>as</code> inside the <code>if</code> block.
CThe variable's type remains unchanged and cannot be used as the checked type.
DThe variable is cast only if it is declared as <code>val</code> outside the <code>if</code> block.
Step-by-Step Solution
Solution:
  1. Step 1: Understand smart cast

    Kotlin automatically casts a variable to the checked type inside an if block when the type is verified.
  2. Step 2: Check variable mutability

    This works only if the variable is immutable (val) or not modified between the check and usage.
  3. Final Answer:

    The variable is automatically cast to the checked type within the if block. -> Option A
  4. Quick Check:

    Smart cast applies automatically inside if after type check [OK]
Quick Trick: Smart casts auto-cast after type checks in if blocks [OK]
Common Mistakes:
MISTAKES
  • Assuming explicit cast is always needed
  • Thinking smart cast applies to mutable variables
  • Believing type remains unchanged after check

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes