Bird
0
0

Which code correctly does this?

hard📝 Application Q15 of 15
Kotlin - Collections Fundamentals

You have a map val scores = mapOf("Alice" to 90, "Bob" to 85) and a list val bonuses = listOf(5, 10). You want to safely get Bob's score and the bonus at index 2, returning 0 if missing, then sum them. Which code correctly does this?

Aval total = (scores["Bob"] ?: 0) + (bonuses.getOrNull(2) ?: 0)
Bval total = (scores.getOrNull("Bob") ?: 0) + (bonuses.getOrNull(2) ?: 0)
Cval total = (scores["Bob"] ?: 0) + (bonuses[2] ?: 0)
Dval total = (scores["Bob"] ?: 0) + bonuses.get(2)
Step-by-Step Solution
Solution:
  1. Step 1: Access map value safely

    scores["Bob"] ?: 0 safely gets Bob's score or 0 if missing.
  2. Step 2: Access list element safely

    bonuses.getOrNull(2) ?: 0 safely gets bonus at index 2 or 0 if out of bounds.
  3. Step 3: Sum the two values

    Adding these two safe values gives the total without errors.
  4. Final Answer:

    val total = (scores["Bob"] ?: 0) + (bonuses.getOrNull(2) ?: 0) -> Option A
  5. Quick Check:

    Safe map + safe list access with ?: for default [OK]
Quick Trick: Use ?: with map and getOrNull for list to avoid errors [OK]
Common Mistakes:
MISTAKES
  • Using bonuses[2] which throws exception if index invalid
  • Using getOrNull on map which is invalid
  • Not providing default fallback

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes