Search code examples
scalamonadsscala-option

Idiomatic scala for getting a single option out of two Options and throwing exception if two are available


val one: Option[Int] = None    
val two = Some(2)

Option(one.getOrElse(two.getOrElse(null))) // Gives me Some(2) which I want

val one = Some(1)
val two = None

Option(one.getOrElse(two.getOrElse(null))) // Gives me Some(1) which I want

val one: Option[Int] = None
val two: Option[Int] = None

Option(one.getOrElse(two.getOrElse(null))) // Gives me None which I want

val one = Some(1)
val two = Some(2)

Option(one.getOrElse(two.getOrElse(null))) // Gives me Some(1) when I want an exception

I briefly looked into the Either type but it seems like it is for "Representing a value of one of two possible types". Am I missing some data structure or Monad? Essentially I want a explicit (and error throwing if both are valuable) get either one if it avaiable or get None


Solution

  • I don't know any pre built to do that, so here is a function:

    def xor[T](x: Option[T], y: Option[T]): Option[T] = (x, y) match {
        case (Some(_), None) => x
        case (None, Some(_)) => y
        case (None, None) => None
        case _ => throw new Exception()
    }