Do something when one option is not empty

I want to calculate something if one of the two options is not empty. Obviously, this can be done by matching patterns, but is there a better way?

(o1, o2) match {
  case (Some(o), None) => Some(compute(o))
  case (None, Some(o)) => Some(compute(o))
  case _ => None
}
+3
source share
4 answers

You can do something like this:

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

But matching patterns is probably the best way.

+3
source

Thanks to the helpful comments from @Suma, I came up with another solution in addition to the current ones:

Since the inputs are always in the form Option(x):

Iterator(Seq(o1,o2).filter(_!=None))
  .takeWhile(_.length==1)
  .map( x => compute(x.head.get))
  .toSeq.headOption

. , .

+1

pedrofurla, o1 orElse o2 map { compute }, xorElse, :

implicit class XorElse[T](o1: Option[T]) {
  def xorElse[A >: T](o2: Option[A]): Option[A] = {
    if (o1.isDefined != o2.isDefined) o1 orElse o2
    else None
  }
}

(o1 xorElse o2).map(compute)

, , - , Seq, . , , , :

  o1.toSeq ++ o2 match {
    case Seq(one) => Some(compute(one))
    case _ => None
  }
+1

,

Seq(o1, o2).flatten match {
  case Seq(o) => Some(compute(o))
  case _ => None
}
0
source

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


All Articles