Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 827
Alessandroempire Avatar asked Dec 03 '22 22:12

Alessandroempire


1 Answers

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.

like image 57
Michael Lorton Avatar answered Dec 20 '22 09:12

Michael Lorton