Bird
0
0

Given a list of nullable Strings, how do you create a list of their lengths, ignoring nulls safely?

hard📝 Application Q9 of 15
Kotlin - Null Safety
Given a list of nullable Strings, how do you create a list of their lengths, ignoring nulls safely?
Aval lengths = list.map { it.length }
Bval lengths = list.mapNotNull { it?.length }
Cval lengths = list.filter { it != null }.map { it.length }
Dval lengths = list.map { it?.length ?: 0 }
Step-by-Step Solution
Solution:
  1. Step 1: Understand list of nullable Strings

    Elements can be null, so safe handling is needed.
  2. Step 2: Use mapNotNull with safe call

    mapNotNull applies function and removes null results safely.
  3. Final Answer:

    val lengths = list.mapNotNull { it?.length } -> Option B
  4. Quick Check:

    mapNotNull + safe call = filtered non-null lengths [OK]
Quick Trick: Use mapNotNull with '?.' to skip nulls safely [OK]
Common Mistakes:
MISTAKES
  • Using map without null filtering
  • Assuming filterNotNull then map is simpler
  • Replacing null lengths with zero instead of skipping

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes