67.scala编程思想笔记——使用Either
欢迎转载,转载请标明出处:http://blog.csdn.net/notbaron/article/details/50458752
源码下载连接请见第一篇笔记。
如果将每个错误都当做异常处理会使代码变得过于凌乱,scala引入了不相交并集来从方法中返回结果。
最初实验称为Either的并集,将left和right组合在一起。Left表示错误,Right携带成功的返回信息。
Either是独立于错误处理而创建的,并且和错误处理没有任何特殊关系。
注意:使用Left和Right不需要任何导入语句。
例如:
import com.atomicscala.AtomicTest._
def f(i:Int) =
if(i == 0)
Left("Divide by zero")
else
Right(24/i)
def test(n:Int) =
f(n) match {
caseLeft(why) => s"Failed: $why"
caseRight(result) => result
}
test(4) is 6
test(5) is 4
test(6) is 4
test(0) is "Failed: Divide by zero"
test(24) is 1
test(25) is 0
left只是一种携带信息的方式,信息可以是异常类型,也可以是其他任何信息。
第二个例子如下:
import com.atomicscala.AtomicTest._
import errors._
def tossEither(which:Int) = which match {
case 1 =>Left(Except1("Reason"))
case 2 =>Left(Except2(11))
case 3 =>Left(Except3("Wanted:", 1.618))
case _ =>Right("OK")
}
def test(n:Int) = tossEither(n) match {
caseLeft(err) => err match {
caseExcept1(why) => s"Except1 $why"
caseExcept2(n) => s"Except2 $n"
caseExcept3(msg, d) =>
s"Except3 $msg $d"
}
case Right(x)=> x
}
test(0) is "OK"
test(1) is "Except1 Reason"
test(2) is "Except2 11"
test(3) is "Except3 Wanted: 1.618"
将异常放到left对象中,可以在left中放置任何信息作为错误报告。
此外可以将Either集合直接map到一个match子句,不需要声明match.
例如:
import com.atomicscala.AtomicTest._
val evens = Range(0,10) map {
case x if x %2 == 0 => Right(x)
case x =>Left(x)
}
evens is Vector(Right(0), Left(1),
Right(2),Left(3), Right(4), Left(5),
Right(6),Left(7), Right(8), Left(9))
evens map {
case Right(x)=> s"Even: $x"
case Left(x)=> s"Odd: $x"
} is "Vector(Even: 0, Odd: 1, Even: 2, " +
"Odd: 3,Even: 4, Odd: 5, Even: 6, " +
"Odd: 7,Even: 8, Odd: 9)"
该map会将match表达式应用于每个元素。