Bird
0
0

You want to create a map that stores student names as keys and their scores as values. You also want to update scores later. Which Kotlin code snippet correctly achieves this?

hard📝 Application Q15 of 15
Kotlin - Collections Fundamentals
You want to create a map that stores student names as keys and their scores as values. You also want to update scores later. Which Kotlin code snippet correctly achieves this?
Aval scores = mutableMapOf("Alice" to 90, "Bob" to 85) scores.add("Alice", 95)
Bval scores = mapOf("Alice" to 90, "Bob" to 85) scores["Alice"] = 95
Cval scores = mapOf("Alice" to 90, "Bob" to 85) scores.put("Alice", 95)
Dval scores = mutableMapOf("Alice" to 90, "Bob" to 85) scores["Alice"] = 95
Step-by-Step Solution
Solution:
  1. Step 1: Choose a mutable map to allow updates

    Since scores need to be updated, mutableMapOf is required.
  2. Step 2: Use correct method to update value

    Assigning with scores["Alice"] = 95 correctly updates the value in a mutable map.
  3. Step 3: Check other options for errors

    val scores = mapOf("Alice" to 90, "Bob" to 85) scores["Alice"] = 95 uses immutable map and tries to update, causing error. val scores = mapOf("Alice" to 90, "Bob" to 85) scores.put("Alice", 95) tries to use put on immutable map, error. val scores = mutableMapOf("Alice" to 90, "Bob" to 85) scores.add("Alice", 95) uses non-existent add method.
  4. Final Answer:

    val scores = mutableMapOf("Alice" to 90, "Bob" to 85) scores["Alice"] = 95 -> Option D
  5. Quick Check:

    mutableMapOf + assignment updates map [OK]
Quick Trick: Use mutableMapOf and bracket assignment to update entries [OK]
Common Mistakes:
MISTAKES
  • Using mapOf when updates are needed
  • Trying to use put on immutable map
  • Using add method which does not exist

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes