Scala Map.updatedWith and Option
Replace a room assignment only when the change slip matches the current entry.
A simple example
Map.updatedWith and Option
- Start with A = 1
- Do this Replace 1 with 2 if it still matches
- Result A = 2
Syntax
rooms.updatedWith(key)(change)
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonChange 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.
object Lesson {
def main(args: Array[String]): Unit = {
val rooms = Map("Class" -> "A2")
val revised = rooms.updatedWith("Class") {
case Some("A2") => Some("B1")
case current => current
}
println(revised("Class"))
}
}
B1
The old assignment is A2, so the change to B1 goes through.
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?
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?
What to watch for
Preserve the previous Option for a stale change slip so that a different room is never overwritten.