Graham Lea Graham Lea - 1 year ago 81
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 = ?

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download