Scala Tuple Option

If I have a Scala tuple Option like:

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

And I always want to always retrieve the value "Some" if it exists, and otherwise get None. The only way to match patterns?

+4
source share
3 answers

There are the following:

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

This will return the first parameter that is defined, or None if none of them.

Edit:

Another way phrases are

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

It is longer, but perhaps more readable.

+10
source

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
}
+4
source

Some, , None

orElse

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

However, this decides what to do if there are two values Some:

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 values Some, such as an exception. Alternatively, consider using better coding for the result type than Option.

+2
source

Source: https://habr.com/ru/post/1675452/


All Articles