Graham Lea Graham Lea - 4 months ago 16
Scala Question

How do I find the min() or max() of two Option[Int]

How would you find

I have my own solution but want to see how others would do it.

val i1: Option[Int] = ...
val i2: Option[Int] = ...
val defaultValue: Int = ...
val minValue = ?


I think this is what you're after:

val minValue = List(i1, i2).flatten match {
  case Nil => defaultValue
  case xs => xs.min

I'd avoid sorted since sorting requires a lot more processing than simply finding the max or min (although it probably doesn't make much difference in this case).