Scala Tutorial Scala References

Scala - Math subtractExact() Method

The Scala Math subtractExact() method returns difference of its arguments. The method can be overloaded and it can take Int and Long arguments. It throws an exception, if the result overflows an Int or a Long.


def subtractExact(x: Int, y: Int): Int = java.lang.Math.subtractExact(x, y)
def subtractExact(x: Long, y: Long): Long = java.lang.Math.subtractExact(x, y)


x Specify the first value.
y Specify the second value.

Return Value

Returns difference of its arguments.


Throws ArithmeticException, if the result overflows an Int or a Long.


In the example below, Math.subtractExact() method is used to find difference of given numbers.

object MainObject {
  def main(args: Array[String]) {
    var x1 : Int = 10;
    var y1 : Int = 20;
    var x2 : Long = 10;
    var y2 : Long = 20;
    println("Math.subtractExact(x1, y1) = "
            + Math.subtractExact(x1, y1)); 
    println("Math.subtractExact(x2, y2) = "
            + Math.subtractExact(x2, y2)); 

The output of the above code will be:

Math.subtractExact(x1, y1) = -10
Math.subtractExact(x2, y2) = -10

❮ Scala - Math Methods