Scala java.lang.Math.subtractExact
Subtract one integer count from another and detect overflow.
A simple example
java.lang.Math.subtractExact
- Start with 5 and 2
- Do this Subtract the second number
- Result 3
object Lesson extends App {
println(java.lang.Math.subtractExact(5, 2))
}
3
Syntax
java.lang.Math.subtractExact(stock, sold)
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 LessonSubtract completed sales from stock
A stock ledger changes as units are sold or an adjustment is reversed. Follow the sign of the operation carefully so the remaining inventory reflects the actual movement of goods.
object Lesson {
def main(args: Array[String]): Unit = {
val stock = 90
val sold = 12
println(java.lang.Math.subtractExact(stock, sold))
}
}
78
Selling twelve of ninety items leaves 78. A negative result can still be valid arithmetic.
Release a school order
A store holds 84 notebooks for the next term. It hands 36 to one class and records what remains.
Using 84 · 36 gives 48 items for this measurement.
Subtract damaged tiles
A studio receives 62 tiles and rejects five with cracked edges. The stock card records the usable count.
Using 62 · 5 gives 57 items for this measurement.
What to watch for
Check the business rule for negative inventory separately from the overflow check.