Scala Tutorial Scala Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Scala - Math max() Method



The Scala Math max() method returns maximum number between the two arguments. The method can be overloaded and it can take Int, Double, Float and Long arguments. If either of the arguments is NaN, then the result is NaN.

Syntax

def max(x: Int, y: Int): Int = java.lang.Math.max(x, y)
def max(x: Long, y: Long): Long = java.lang.Math.max(x, y)
def max(x: Float, y: Float): Float = java.lang.Math.max(x, y)
def max(x: Double, y: Double): Double = java.lang.Math.max(x, y)

Parameters

x Specify value to compare.
y Specify value to compare.

Return Value

Returns the numerically maximum value.

Exception

NA.

Example:

In the example below, max() method is used to find out the maximum value between the two arguments.

import scala.math._

object MainObject {
  def main(args: Array[String]) {
    println(s"max(10, 20) = ${max(10, 20)}");   
    println(s"max(10.5, 5.5) = ${max(10.5, 5.5)}"); 
    println(s"max(10, Double.NaN) = ${max(10, Double.NaN)}");  
    println("max(10.5, Double.PositiveInfinity) = "
            + max(10.5, Double.PositiveInfinity));
    println("max(10.5, Double.NegativeInfinity) = "
            + max(10.5, Double.NegativeInfinity));
  }
}

The output of the above code will be:

max(10, 20) = 20
max(10.5, 5.5) = 10.5
max(10, Double.NaN) = NaN
max(10.5, Double.PositiveInfinity) = Infinity
max(10.5, Double.NegativeInfinity) = 10.5

❮ Scala - Math Methods

5