1

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

pathikrit
  • 32,469
  • 37
  • 142
  • 221
  • 3
    [`orElse`](http://www.scala-lang.org/api/2.10.2/index.html#scala.Option) is not sufficient? – user2864740 Apr 18 '14 at 21:17
  • 2
    The [source of `orElse`](https://github.com/scala/scala/blob/v2.10.2/src/library/scala/Option.scala#L256), just for reference. – Dylan Apr 18 '14 at 21:26

3 Answers3

13

It's already defined for Option:

def or[A](x: Option[A], y: Option[A]) = x orElse y
Noah
  • 13,821
  • 4
  • 36
  • 45
2

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
stew
  • 11,276
  • 36
  • 49
0

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)
Melvic Ybanez
  • 1,893
  • 4
  • 19
  • 26