例如,我有两个Try
对象。如果一个或另一个失败,我想获取错误并以相同的方式处理它:
val t1 = Try(throw new Exception("one"))
val t2 = Try(throw new Exception("two"))
(t1, t2) match {
case (Success(_), Success(_)) => println("It's ok")
case _ : Failure(e), _) | (_, Failure(e) => // Compile error here
println("Fail", e) // Doesn't matter from where e was come
}
是否可以在两个失败选项中使用相同的e
编写此代码?
答案 0 :(得分:5)
您不能以这种方式组合匹配模式。您可以通过以下方式实现所需的行为:
t1.flatMap(_ => t2) match {
case Success(_) => println("It's ok")
case Failure(e) => prinltn("Fail", e)
}
答案 1 :(得分:0)
基于@Nyavro answer的另一种便捷的方法是将多个try组合到一个try通道中以进行理解:
Msg 8120, Level 16, State 1, Line 253
Column 'RENT.dvdID' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause.