Kotlin MutableMap.remove with expected value
Release a locker after checking that its current owner is the student returning it.
A simple example
MutableMap.remove with expected value
- Start with A = 1
- Do this Remove A if its value is 1
- Result A is absent
Syntax
claims.remove(key, owner)
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.jarRelease a locker only for its recorded owner
A school uses locker numbers as keys and student names as values. When Mira returns her locker, the desk clears the assignment only if the current register still names Mira.
fun main() {
val claims = mutableMapOf("L2" to "Mira")
if (claims.remove("L2", "Mira")) println("Released")
}
Released
Locker L2 belongs to Mira, so the register accepts the return.
Return a locker key
A locker has a single claim and its registered holder returns the key. The clerk removes the claim only when the recorded owner matches the claimant. How many claims remain?
Keep a reserved headset
A different student tries to release the only headset claim. The clerk removes the claim only when the recorded owner matches the claimant. How many claims remain?
What to watch for
The two-argument form requires both a matching key and value. The one-argument form removes solely by key.