Alessandroempire
Alessandroempire

Reputation: 1699

Scala Tuple Option

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?

Upvotes: 4

Views: 2066

Answers (3)

Michael Lorton
Michael Lorton

Reputation: 44436

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.

Upvotes: 10

ashawley
ashawley

Reputation: 4284

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.

Upvotes: 2

mfirry
mfirry

Reputation: 3692

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
}

Upvotes: 4

Related Questions