sealed abstract class Either[+A, +B] extends Product with Serializable
它有两个子类Left和Right:
/** The left side of the disjoint union, as opposed to the [[scala.util.Right]] side.
*
* @author <a href="mailto:research@workingmouse.com">Tony Morris</a>, Workingmouse
*/
final case class Left[+A, +B](@deprecatedName('a, "2.12.0") value: A) extends Either[A, B] {
def isLeft = true
def isRight = false
@deprecated("Use .value instead.", "2.12.0") def a: A = value
}
/** The right side of the disjoint union, as opposed to the [[scala.util.Left]] side.
*
* @author <a href="mailto:research@workingmouse.com">Tony Morris</a>, Workingmouse
*/
final case class Right[+A, +B](@deprecatedName('b, "2.12.0") value: B) extends Either[A, B] {
def isLeft = false
def isRight = true
@deprecated("Use .value instead.", "2.12.0") def b: B = value
}
我们通过这两个子类从两个可能的元素中选择一种。
Either 概念的产生时间早于Scala。很长时间以来它被认为是抛出异常的一种替代方案。 为了尊重历史习惯,当Either 用于表示错误标志或某一对象值时,Left 值用于表示错误标志,如:信息字符串或下层库抛出的异常;而正常返回时则使用Right 对象。很明显,Either 可以用于任何需要持有某一个或另一个对象的场景中,而这两个对象的类型可能不同。