Library contents

Kotlin MutableMap.set and get

Update a shelf count and retrieve it using the product label.

A simple example

MutableMap.set and get

  1. Start with A = 1
  2. Do this Store 2 at key A
  3. Result A = 2
Looking up the same key now returns the new value.

Syntax

Kotlin syntax
stock[key] = count
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Update the count for a shelf label

A shop keeps one inventory entry for each shelf label. After a second delivery arrives, the clerk replaces the old tea count and looks up the current total using the same label.

From the programstock["Tea"] = 7
Result7
Lesson.kt
fun main() {
    val stock = mutableMapOf("Tea" to 3)
    stock["Tea"] = 7
    println(stock.getValue("Tea"))
}
Output
7

Updating the Tea key changes the recorded count from three to seven.

Advertisements

Revise a locker assignment

A rental desk moves the green key from locker 6 to locker 9. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?

Givengreen → 6, then green → 9
Worked result9

Correct a menu price

A café changes its soup price after reprinting the menu. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?

Givensoup → 5, then soup → 6
Worked result6

What to watch for

A normal key lookup returns a nullable value. getValue throws if a required product is absent.

Documentation for MutableMap.set and get