Bird
0
0

How can you safely cast an Any type to String in Kotlin without risking a ClassCastException?

hard📝 Application Q9 of 15
Kotlin - Data Types
How can you safely cast an Any type to String in Kotlin without risking a ClassCastException?
Aval s = value.toString()
Bval s = value as String
Cval s = value as? String
Dval s = value is String
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe cast operator

    as? attempts to cast and returns null if it fails, avoiding exceptions.
  2. Step 2: Compare with unsafe cast

    as throws exception if cast fails. toString() converts to string but not cast. is checks type but does not cast.
  3. Final Answer:

    val s = value as? String -> Option C
  4. Quick Check:

    Safe cast uses as? operator [OK]
Quick Trick: Use as? for safe casting to avoid exceptions [OK]
Common Mistakes:
MISTAKES
  • Using as without checking type
  • Confusing toString with casting
  • Using is for casting instead of checking

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes