Bird
0
0

Which Kotlin expression safely accesses the value for key "x" in a map and returns 0 if the key is missing?

easy📝 Conceptual Q2 of 15
Kotlin - Collections Fundamentals
Which Kotlin expression safely accesses the value for key "x" in a map and returns 0 if the key is missing?
Amap["x"]!!
Bmap.get("x")
Cmap["x"] ?: 0
Dmap.getValue("x")
Step-by-Step Solution
Solution:
  1. Step 1: Understand map access and default values

    Using map["x"] returns the value or null if key is missing. The Elvis operator ?: provides a default value if null.
  2. Step 2: Check each option

    map["x"] ?: 0 uses ?: 0 to return 0 if key "x" is missing. map.get("x") returns nullable value without default. map["x"]!! forces non-null and throws if missing. map.getValue("x") throws if key missing.
  3. Final Answer:

    map["x"] ?: 0 -> Option C
  4. Quick Check:

    Safe map access with default = map["x"] ?: 0 [OK]
Quick Trick: Use ?: to provide default when accessing nullable map values [OK]
Common Mistakes:
MISTAKES
  • Using !! which throws exception if key missing
  • Using getValue which throws if key missing
  • Not providing default value for null

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes