Bird
0
0

Given a mutable map val map = mutableMapOf("x" to 5), which code adds a new key "y" with value 10 only if "y" is not already present?

hard📝 Application Q9 of 15
Kotlin - Collections Fundamentals
Given a mutable map val map = mutableMapOf("x" to 5), which code adds a new key "y" with value 10 only if "y" is not already present?
Amap.putIfAbsent("y", 10)
Bmap.put("y", 10)
Cmap["y"] = 10
Dmap.add("y", 10)
Step-by-Step Solution
Solution:
  1. Step 1: Understand putIfAbsent behavior

    putIfAbsent adds the key-value only if key is missing.
  2. Step 2: Check other methods

    map["y"] = 10 and put() overwrite existing keys; add() is invalid for maps.
  3. Final Answer:

    map.putIfAbsent("y", 10) -> Option A
  4. Quick Check:

    Use putIfAbsent to add only if key missing = C [OK]
Quick Trick: Use putIfAbsent to avoid overwriting existing keys [OK]
Common Mistakes:
MISTAKES
  • Using map["y"] = 10 which overwrites
  • Using invalid add() method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes