Scala Map.updatedWith
Decrease a stock balance only when the product is already on the ledger.
A simple example
Map.updatedWith
- Start with A = 3
- Do this Subtract 1 for existing A
- Result A = 2
Syntax
stock.updatedWith(key)(_.map(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 LessonReduce only the stock that is on the ledger
A storeroom issues one mug and receives a request for an unlisted bowl. The clerk should reduce the mug balance but leave the unlisted product out of the ledger.
object Lesson {
def main(args: Array[String]): Unit = {
var stock = Map("Mug" -> 3)
for (item <- List("Mug", "Bowl")) {
stock = stock.updatedWith(item)(_.map(_ - 1))
}
println(stock("Mug"))
}
}
2
Mug falls from three to two. The unlisted Bowl receives no mapping.
Issue paintbrushes
A class has fourteen brushes under its art-room key. An existing stock record is reduced by the number handed out. What value is written back under the same key?
Update a mug count
The café has eight cups on its stock card. An existing stock record is reduced by the number handed out. What value is written back under the same key?
What to watch for
Returning None removes a mapping. Mapping over an absent value here leaves it absent.