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
我简要地研究了Either 类型,但它似乎是为了“表示两种可能类型之一的值”。我是否缺少一些数据结构或 Monad?本质上,我想要一个明确的(如果两者都有值(value),则抛出错误)获取其中一个(如果可用)或获取 None
最佳答案
我不知道有任何预先构建来做到这一点,所以这里有一个函数:
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()
}
关于scala - 用于从两个选项中获取一个选项并在两个选项可用时抛出异常的惯用 scala,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26065300/