Bird
0
0

How can you safely cast a nullable Any? variable to String? and provide a default value if the cast fails?

hard📝 Application Q9 of 15
Kotlin - Null Safety

How can you safely cast a nullable Any? variable to String? and provide a default value if the cast fails?

val obj: Any? = getObject()
val str: String = (obj ___) ?: "default"
Aas String
Bas? String
Cas? String?
Das String?
Step-by-Step Solution
Solution:
  1. Step 1: Use safe cast to nullable String

    The safe cast as? returns a nullable String or null if cast fails.
  2. Step 2: Use Elvis operator for default

    The Elvis operator ?: provides "default" if the cast returns null.
  3. Final Answer:

    as? String -> Option B
  4. Quick Check:

    Safe cast with default uses 'as?' and '?:' = A [OK]
Quick Trick: Use 'as?' with '?:' to provide default on cast failure [OK]
Common Mistakes:
MISTAKES
  • Using unsafe cast causing exceptions
  • Incorrect nullable type syntax
  • Omitting default value for null

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes