操作选项的最佳方法是使用for 表达式。
for (a1 <- a; b1 <- b) yield a1.compare(b1) // Some(-1)
如果至少有一个数字是None,则结果是None。
val x: Option[Int] = None
for (a1 <- a; b1 <- x) yield a1.compare(b1) // None
比较函数可以定义为
def compare(a: Option[Int], b: Option[Int]) = {
for (a1 <- a; b1 <- b) yield a1.compare(b1)
}.get
更新:
如果你想要 Nones,你可以使用模式匹配:
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))