It's already defined for Option
:
def or[A](x: Option[A], y: Option[A]) = x orElse y
سؤال
I want to do something like this:
def or[A](x: Option[A], y: Option[A]) = x match {
case None => y
case _ => x
}
What is the idiomatic way to do this? The best I can come up with was Seq(x, y).flatten.headOption
المحلول
It's already defined for Option
:
def or[A](x: Option[A], y: Option[A]) = x orElse y
نصائح أخرى
in scalaz, you can use the Plus typeclass for this:
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
If, for some reason, you don't want to use orElse, well, there's always another way to do it in Scala.
def or[A](xOpt: Option[A], yOpt: Option[A]) = xOpt.map(Some(_)).getOrElse(yOpt)