Scala java.lang.Math.decrementExact
Subtract one from a counter and detect overflow at the lower limit.
A simple example
java.lang.Math.decrementExact
- Start with 3
- Do this Subtract 1
- Result 2
object Lesson extends App {
println(java.lang.Math.decrementExact(3))
}
2
Syntax
java.lang.Math.decrementExact(places)
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 LessonReserve one available place
A desk issues numbered places one at a time. Check the next or remaining count at the edge of its allowed range so a full counter cannot wrap into an apparently valid booking.
object Lesson {
def main(args: Array[String]): Unit = {
val places = 12
println(java.lang.Math.decrementExact(places))
}
}
11
Taking one of twelve places leaves eleven.
Release one museum headset
The desk has seven headsets available at opening. It hands one to a visitor and updates the count.
Using 7 gives 6 for this measurement.
Use the final appointment slot
A clinic calendar has one slot left today. A booking consumes that slot and the calendar updates availability.
Using 1 gives 0 for this measurement.
What to watch for
Zero can become minus one without arithmetic overflow. Validate availability before reserving.