Ole*_*leg 0 scala pattern-matching
例如,我有两个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
}
Run Code Online (Sandbox Code Playgroud)
是否可以e
在两个失败选项编译中使用相同的代码?
您不能以这种方式组合匹配模式.您可以通过以下方式实现所需的行为:
t1.flatMap(_ => t2) match {
case Success(_) => println("It's ok")
case Failure(e) => prinltn("Fail", e)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
57 次 |
最近记录: |