質問

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