Scala java.lang.Math.absExact
Return the magnitude of a signed integer, reporting an unrepresentable result.
A simple example
java.lang.Math.absExact
- Start with −3
- Do this Measure distance from zero
- Result 3
object Lesson extends App {
println(java.lang.Math.absExact(-3))
}
3
Syntax
java.lang.Math.absExact(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 LessonMeasure a stock change and detect overflow
Two signed readings can be individually valid while their difference or magnitude exceeds the destination type. Check the arithmetic at its boundaries before reporting the size of the change.
object Lesson {
def main(args: Array[String]): Unit = {
val change = -18
println(java.lang.Math.absExact(change))
}
}
18
The size of a drop of eighteen items is eighteen.
Count missing lab probes
A storeroom log records an adjustment of minus 14 probes after an audit. The supervisor needs its magnitude for a discrepancy ticket.
The absolute magnitude fits in a signed integer.
Close a balanced shift
A till already balances when its last receipt is entered. The auditor still needs to record the discrepancy as a number.
Zero has magnitude zero.
What to watch for
The minimum signed integer raises ArithmeticException. Widen first if its magnitude should be representable.