Bird
0
0

Given a list of Any objects, how can you safely cast all elements to String and collect only the successful casts?

hard📝 Application Q8 of 15
Kotlin - Null Safety

Given a list of Any objects, how can you safely cast all elements to String and collect only the successful casts?

val items: List = listOf("a", 1, "b", 2)
// Fill in the blank
val strings = items.mapNotNull { it ___ }
Aas? Int
Bas String
Cas? String
DtoString()
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe cast in mapNotNull

    Using as? returns nullable String or null if cast fails.
  2. Step 2: Use mapNotNull to filter nulls

    mapNotNull collects only non-null results, so only successful casts remain.
  3. Final Answer:

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

    Safe cast with mapNotNull filters successful casts = D [OK]
Quick Trick: Use 'as?' inside mapNotNull to filter successful casts [OK]
Common Mistakes:
MISTAKES
  • Using unsafe cast causing exceptions
  • Using toString() which converts all to string
  • Casting to wrong type

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes