문제

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top