【问题标题】:"Or"-ing two Options in Scala?“或”-ing Scala 中的两个选项?
【发布时间】:2014-04-18 21:13:38
【问题描述】:
我想做这样的事情:
def or[A](x: Option[A], y: Option[A]) = x match {
case None => y
case _ => x
}
这样做的惯用方法是什么?我能想到的最好的是Seq(x, y).flatten.headOption
【问题讨论】:
标签:
scala
functional-programming
scalaz
scala-option
【解决方案1】:
已经为Option定义了:
def or[A](x: Option[A], y: Option[A]) = x orElse y
【解决方案2】:
在 scalaz 中,您可以为此使用 Plus 类型类:
scala> 1.some <+> 2.some
res1: Option[Int] = Some(1)
scala> none[Int] <+> 2.some
res2: Option[Int] = Some(2)
scala> none[Int] <+> none[Int]
res3: Option[Int] = None
【解决方案3】:
如果出于某种原因,您不想使用 orElse,那么,在 Scala 中总是有另一种方法。
def or[A](xOpt: Option[A], yOpt: Option[A]) = xOpt.map(Some(_)).getOrElse(yOpt)