Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How would you find minValue below? 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 = ?
like image 374
Graham Lea Avatar asked Sep 28 '12 12:09

Graham Lea


1 Answers

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

like image 87
Luigi Plinge Avatar answered Oct 17 '22 22:10

Luigi Plinge