Scala编程:函数式与面向对象的深度探索
在Scala编程中,我们常常会遇到处理错误和异常的场景。 Either 类型为我们提供了一种有效的方式来处理可能出现的失败情况。
Either类型的使用
Either 类型可以明确表示可能的失败模式。以下是一个示例函数 addInts2 :
def addInts2(s1: String, s2: String): Either[NumberFormatException,Int]=
try {
Right(s1.toInt + s2.toInt)
} catch {
case nfe: NumberFormatException => Left(nfe)
}
我们可以通过以下方式调用这个函数:
println(addInts2("1", "2")) // 输出: Right(3)
println(addInts2("1", "x")) // 输出: Left(java.lang.NumberFormatException: For input string: "x")
println(addInts2("x", "2")) // 输出: Left(java.lang.NumberFormatException: For input string: "x")
Either
Scala函数式与面向对象编程探索
超级会员免费看
订阅专栏 解锁全文
52

被折叠的 条评论
为什么被折叠?



