What is Math.min() in Scala?

The min() function returns the smallest value among the two numbers sent as parameters. The image below shows a visual representation of the min() function.

Visual representation of min() function

The following module is required for this function:

import scala.math._

Syntax

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

Parameters

The min() function takes two numbers as parameters.

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

Return value

The min() function returns the smallest value from the two numbers sent as parameters.

  • If either of the two values is NaN, or both are NaN, then min() returns NaN.

Code

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

Free Resources