What is Math.max() in Scala?

The max() function returns the largest value out of the two numbers sent as a parameter. Figure 1 shows a visual representation of the max() function.

Figure 1: Visual representation of max() function

The following module is required for this function:

import scala.math._

Syntax

type max(type num-1, type num-2)
// Type can be : Int, Float, Double, Long

Parameter

The max() function takes two numbers as a parameter.

The numbers can be of type Int, Double, Float, or Long.

Return value

The max() function returns the largest value from the two numbers sent as a parameter.

  • If either of the two parameter values is NaN, or if both are NaN, then it returns NaN.

Code

import scala.math._
object Main extends App {
// two positive numbers
println(s"The value of max(10, 0) = ${max(10, 0)}");
//one positive and the other negative
println(s"The value of max(4, -6) = ${max(4, -6)}");
println(s"The value of max(Double.PositiveInfinity,Double.PositiveInfinity) = ${max(Double.PositiveInfinity,Double.NegativeInfinity)}");
// both negative numbers
println(s"The value of max(-10, -9) = ${max(-10, -9)}");
// both double numbers
println(s"The value of max(12.234,1.2345) = ${max(12.234,1.2345)}");
// one int and the other double
println(s"The value of max(12.234,1) = ${max(12.234,1)}");
//error ouput
println(s"The value of max(Double.NaN,Double.NaN) = ${max(Double.NaN,Double.NaN)}");
}

Free Resources