Scala java.lang.Math.negateExact
Reverse the sign of an integer with an overflow check.
A simple example
java.lang.Math.negateExact
- Start with 3
- Do this Change the sign
- Result −3
object Lesson extends App {
println(java.lang.Math.negateExact(3))
}
-3
Syntax
java.lang.Math.negateExact(adjustment)
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 LessonReverse an inventory adjustment
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 adjustment = -18
println(java.lang.Math.negateExact(adjustment))
}
}
18
Reversing a deduction of eighteen restores eighteen units.
Reverse a mistaken delivery
A librarian posted an increase of nine books to the wrong shelf. She enters the opposite signed adjustment to undo the entry.
Using 9 gives -9 for this measurement.
Undo a duplicate withdrawal
The stock journal includes a duplicate debit of four items. Its reversal needs the same magnitude with the opposite sign.
Using -4 gives 4 for this measurement.
What to watch for
The most negative signed integer has no positive counterpart of the same width.