Bird
0
0

What happens if a safe cast using as? fails in Kotlin?

easy📝 Conceptual Q1 of 15
Kotlin - Null Safety

What happens if a safe cast using as? fails in Kotlin?

AIt throws a ClassCastException
BIt converts the object to a string automatically
CIt returns the original object unchanged
DIt returns null instead of throwing an exception
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe cast behavior

    The safe cast operator as? tries to cast an object to a type but returns null if the cast is not possible.
  2. Step 2: Compare with unsafe cast

    Unlike the unsafe cast as, which throws an exception on failure, as? safely returns null.
  3. Final Answer:

    It returns null instead of throwing an exception -> Option D
  4. Quick Check:

    Safe cast returns null on failure = B [OK]
Quick Trick: Safe cast returns null if it can't convert [OK]
Common Mistakes:
MISTAKES
  • Confusing safe cast with unsafe cast throwing exceptions
  • Assuming safe cast returns original object on failure
  • Thinking safe cast converts types automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes