Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something when exactly one option is non-empty

I want to compute something if exactly one of two options is non-empty. Obviously this could be done by a pattern match, but is there some better way?

(o1, o2) match {
  case (Some(o), None) => Some(compute(o))
  case (None, Some(o)) => Some(compute(o))
  case _ => None
}
like image 349
Suma Avatar asked Apr 08 '17 20:04

Suma


1 Answers

You could do something like this:

if (o1.isEmpty ^ o2.isEmpty)
  List(o1,o2).flatMap(_.map(x=>Some(compute(x)))).head
else
  None

But pattern matching is probably the better way to go.

like image 162
jwvh Avatar answered Sep 28 '22 15:09

jwvh