Library contents

Kotlin MutableMap.replace on the JVM

Replace a room assignment only when the change slip matches the current entry.

A simple example

MutableMap.replace on the JVM

  1. Start with A = 1
  2. Do this Replace 1 with 2 if it still matches
  3. Result A = 2
The comparison and the replacement refer to the same key.

Syntax

Kotlin syntax
rooms.replace(key, expected, replacement)
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

Change a room assignment only if it is still current

A receptionist holds a change slip that moves a class from room A2 to B1. Before updating the board, she checks that the displayed entry still matches the room printed on her slip.

ResultB1
Lesson.kt
fun main() {
    val rooms = java.util.HashMap(mapOf("Class" to "A2"))
    rooms.replace("Class", "A2", "B1")
    println(rooms.getValue("Class"))
}
Output
B1

The old assignment is A2, so the change to B1 goes through.

Advertisements

Change a duty room

The old assignment still matches the room printed on the request. The desk replaces the value only when the recorded value matches the expected one. Which value remains?

GivenRecorded West · replace West with East
Worked resultEast

Ignore a stale booking change

A newer room assignment has already been saved. The desk replaces the value only when the recorded value matches the expected one. Which value remains?

GivenRecorded Hall · replace East with Lab
Worked resultHall

What to watch for

This conditional operation relies on value equality. The example runs on Kotlin/JVM.

Documentation for MutableMap.replace on the JVM