Scala Tutorial Scala References

Scala - Math addExact() Method



The Scala Math addExact() method returns sum 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.

Syntax

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

Parameters

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

Return Value

Returns sum of its arguments.

Exception

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

Example:

In the example below, Math.addExact() method is used to add 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.addExact(x1, y1) = "
            + Math.addExact(x1, y1)); 
    println("Math.addExact(x2, y2) = "
            + Math.addExact(x2, y2)); 
  }
}

The output of the above code will be:

Math.addExact(x1, y1) = 30
Math.addExact(x2, y2) = 30

❮ Scala - Math Methods