【发布时间】:2018-06-28 06:23:44
【问题描述】:
例如,我有两个 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 编译这段代码?
【问题讨论】:
-
你不能——你可以把期货放在一个列表中并像stackoverflow.com/questions/15495678/flatten-scala-try一样将其展平
-
把两个失败的案例分开是不是很糟糕?
case (Failure(e), _) => println(s"Fail $e") case (_, Failure(e)) => println(s"Fail $e") -
@mfirry 其实,不是很糟糕,但我想知道这是否可能。