Bird
0
0

How can you safely use smart casts with a nullable variable inside an if statement?

hard📝 Application Q9 of 15
Kotlin - Control Flow as Expressions
How can you safely use smart casts with a nullable variable inside an if statement?
ADirectly access properties without null check.
BCheck for null with <code>!= null</code> before accessing properties.
CUse <code>!!</code> operator to force unwrap.
DAssign variable to a new non-nullable variable without check.
Step-by-Step Solution
Solution:
  1. Step 1: Understand nullable smart casts

    Kotlin smart casts work after null checks to ensure safety.
  2. Step 2: Use != null check

    Checking variable != null allows smart cast to non-null type inside the block.
  3. Final Answer:

    Check for null with != null before accessing properties. -> Option B
  4. Quick Check:

    Null check enables safe smart cast [OK]
Quick Trick: Always check for null before smart casting nullable vars [OK]
Common Mistakes:
MISTAKES
  • Accessing nullable without null check
  • Using !! operator unsafely
  • Assuming assignment removes nullability

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes