Bird
0
0

Why is the safe cast operator as? preferred over the unsafe cast as in Kotlin when dealing with uncertain types?

hard📝 Conceptual Q10 of 15
Kotlin - Null Safety

Why is the safe cast operator as? preferred over the unsafe cast as in Kotlin when dealing with uncertain types?

ABecause it prevents runtime exceptions by returning null on failure
BBecause it automatically converts incompatible types
CBecause it is faster than unsafe cast
DBecause it throws a more descriptive exception
Step-by-Step Solution
Solution:
  1. Step 1: Understand unsafe cast behavior

    The unsafe cast as throws a ClassCastException if the cast fails.
  2. Step 2: Understand safe cast benefits

    The safe cast as? returns null instead of throwing, preventing runtime crashes.
  3. Final Answer:

    Because it prevents runtime exceptions by returning null on failure -> Option A
  4. Quick Check:

    Safe cast avoids exceptions by returning null = B [OK]
Quick Trick: Safe cast avoids exceptions by returning null [OK]
Common Mistakes:
MISTAKES
  • Thinking safe cast converts types automatically
  • Assuming safe cast is faster
  • Confusing exception behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes