4

If I have Scala tuple Option of the likes:

(Some(1), None)
(None, Some(1))
(None, None) 

And I want always to extract always the "Some" value if it exists, and otherwise get the None. The only way with pattern matching?

dbc
  • 104,963
  • 20
  • 228
  • 340
Alessandroempire
  • 1,640
  • 4
  • 31
  • 54

3 Answers3

10

There is this:

def oneOf[A](tup: (Option[A], Option[A])) = tup._1.orElse(tup._2)

That will return the first option that is defined, or None if neither is.

Edit:

Another way to phrase the same thing is

def oneOf[A](tup:  (Option[A], Option[A])) = 
   tup match { case (first, second) => first.orElse(second) }

It's longer, but perhaps more readable.

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
4

This should work:

def f(t: (Option[Int], Option[Int])): Option[Int] = t match {
  case (Some(n), _) => Some(n)
  case (_, Some(n)) => Some(n)
  case _ => None
}
mfirry
  • 3,634
  • 1
  • 26
  • 36
2

I want always to extract always the Some value if it exists, and otherwise get the None

You can just use orElse

def orOption[T](p: (Option[T], Option[T])): Option[T] = {
  val (o1, o2) = p
  o1 orElse o2
}

However, this does decide what to do if there exists two Some values:

scala> orOption((Some(1), Some(2)))
res0: Option[Int] = Some(1)

You should probably use pattern matching and then decide what to do if there are two Some values, like throw an exception. Alternatively, consider using a better encoding for the result type than Option.

ashawley
  • 4,195
  • 1
  • 27
  • 40