Search code examples
scalamathminimum

Scala: How to find the minimum of more than 2 elements?


Since the Math.min() function only allows for the use of 2 elements, I was wondering if there is maybe another function which can calculate the minimum of more than 2 elements.

Thanks in advance!


Solution

  • If you have multiple elements you can just chain calls to the min method:

    Math.min(x, Math.min(y, z))
    

    Since scala adds the a min method to numbers via implicits you could write the following which looks much fancier:

    x min y min z
    

    If you have a list of values and want to find their minimum:

    val someNumbers: List[Int] = ???
    val minimum = someNumbers.min
    

    Note that this throws an exception if the list is empty. From scala 2.13.x onwards, there will be a minOption method to handle such cases gracefully. For older versions you could use the reduceOption method as workaround:

    someNumbers.reduceOption(_ min _)
    someNumbers.reduceOption(Math.min)