Bird
0
0

You have a nullable list of nullable Strings: val items: List?. How do you safely print the length of the first item or print 0 if the list or first item is null?

hard📝 Application Q15 of 15
Kotlin - Null Safety
You have a nullable list of nullable Strings: val items: List?. How do you safely print the length of the first item or print 0 if the list or first item is null?
Aprintln(items?.get(0)?.length ?: 0)
Bprintln(items[0].length)
Cprintln(items!!.get(0)!!.length)
Dprintln(items?.get(0).length ?: 0)
Step-by-Step Solution
Solution:
  1. Step 1: Analyze nullable types

    items can be null, and its elements can be null. So both list and first item need safe calls.
  2. Step 2: Use safe calls and Elvis operator

    items?.get(0)?.length ?: 0 safely accesses first item length or returns 0 if null.
  3. Final Answer:

    println(items?.get(0)?.length ?: 0) -> Option A
  4. Quick Check:

    Safe calls chain + fallback = safe nullable access [OK]
Quick Trick: Chain ?. for each nullable and use ?: for default [OK]
Common Mistakes:
MISTAKES
  • Using !! which throws exception if null
  • Missing safe call on first item
  • Assuming list or item can't be null

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes