# Scala教程之:Either

04/11 20:52

``sealed abstract class Either[+A, +B] extends Product with Serializable``

``````/** 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。很长时间以来它被认为是抛出异常的一种替代方案。

``````def positive(i: Int): Either[String,Int] =
if (i > 0) Right(i) else Left(s"nonpositive number \$i")

for {
i1 <- positive(5).right
i2 <- positive(10 * i1).right
i3 <- positive(25 * i2).right
i4 <- positive(2  * i3).right
} yield (i1 + i2 + i3 + i4)
// Returns: scala.util.Either[String,Int] = Right(3805)

for {
i1 <- positive(5).right
i2 <- positive(-1 * i1).right   // EPIC FAIL!
i3 <- positive(25 * i2).right
i4 <- positive(-2 * i3).right   // EPIC FAIL!
} yield i1 + i2 + i3 + i4
// Returns: scala.util.Either[String,Int] = Left(nonpositive number -5)``````

``````scala> def addInts(s1: String, s2: String): Int =
| s1.toInt + s2.toInt
scala> for {
| i <- 1 to 3
| j <- 1 to i
1+1 = 2
2+1 = 3
2+2 = 4
3+1 = 4
3+2 = 5
204 ｜ 第7 章
3+3 = 6
java.lang.NumberFormatException: For input string: "x"``````

``````scala> def addInts2(s1: String, s2: String): Either[NumberFormatException,Int]=
| try {
| Right(s1.toInt + s2.toInt)
| } catch {
| case nfe: NumberFormatException => Left(nfe)
| }
Right(3)
Left(java.lang.NumberFormatException: For input string: "x")
Left(java.lang.NumberFormatException: For input string: "x")``````

0
0 收藏

0 评论
0 收藏
0