The best way to manipulate Options is using for
expressions.
for (a1 <- a; b1 <- b) yield a1.compare(b1) // Some(-1)
If at least one of the numbers is None
, the result is None
.
val x: Option[Int] = None
for (a1 <- a; b1 <- x) yield a1.compare(b1) // None
A compare function may be defined as
def compare(a: Option[Int], b: Option[Int]) = {
for (a1 <- a; b1 <- b) yield a1.compare(b1)
}.get
Updated:
If you want the Nones you can use pattern matching:
def compare(a: Option[Int], b: Option[Int]) = (a, b) match {
case (Some(a), Some(b)) => a.compare(b)
case (None, None) => 0
case (None, _) => -1 // None comes before
case (_, None) => 1
}
val list: List[Option[Int]] = List(List(Some(1), None, Some(4), Some(2), None))
val list2 = list.sortWith(compare(_, _) < 0)
// list2 = List(None, None, Some(1), Some(2), Some(4))