Bird
0
0

How can you safely iterate over a Java List platform type that might be null in Kotlin?

hard📝 Application Q9 of 15
Kotlin - Null Safety
How can you safely iterate over a Java List platform type that might be null in Kotlin?
AjavaList!!.forEach { println(it) }
BjavaList.forEach { println(it) }
CjavaList?.forEach { println(it) } ?: println("Empty list")
Dfor (item in javaList) println(item)
Step-by-Step Solution
Solution:
  1. Step 1: Recognize javaList may be null

    Platform types from Java can be null, so safe call is needed.
  2. Step 2: Use safe call with fallback

    Using ?.forEach runs loop if not null; ?: prints fallback message if null.
  3. Final Answer:

    javaList?.forEach { println(it) } ?: println("Empty list") -> Option C
  4. Quick Check:

    Safe call with fallback handles nullable platform collections [OK]
Quick Trick: Use ?. and ?: to safely handle nullable Java collections [OK]
Common Mistakes:
MISTAKES
  • Calling forEach without null check
  • Using !! risking exceptions
  • Ignoring null fallback

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes