Bird
0
0

You have a list of nullable strings: val names: List = listOf("Anna", null, "Bob"). How do you safely print the length of the third element or print 0 if it is null?

hard📝 Application Q8 of 15
Kotlin - Collections Fundamentals
You have a list of nullable strings: val names: List = listOf("Anna", null, "Bob"). How do you safely print the length of the third element or print 0 if it is null?
Aprintln(names[2]!!.length)
Bprintln(names[2].length ?: 0)
Cprintln(names.getOrNull(2)?.length ?: 0)
Dprintln(names.get(2).length)
Step-by-Step Solution
Solution:
  1. Step 1: Access third element safely

    Use getOrNull(2) to safely get the third element or null if out of bounds.
  2. Step 2: Use safe call and default

    Use safe call ?.length to get length if not null, else null. Then use Elvis operator ?: 0 to default to 0.
  3. Final Answer:

    println(names.getOrNull(2)?.length ?: 0) -> Option C
  4. Quick Check:

    Safe access with getOrNull and ?.length with default [OK]
Quick Trick: Combine getOrNull and ?. to safely access nullable list elements [OK]
Common Mistakes:
MISTAKES
  • Using !! which throws if null
  • Not using getOrNull causing exceptions
  • Using ?: on non-nullable types incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes