有没有办法访问finally块中try / catch块中创建的val?或者是最终块超出范围。
def myTryCatch: Either[Exception, String] = {
try {
val w = runOrFailWithException("Please work...")
Right(w)
} catch {
case ex: Exception => {
Left(ex)
}
}
finally {
// How do I get access to Left or Right in my finally block.
// This does not work
_ match {
case Right(_) =>
case Left(_) =>
}
}
}
答案 0 :(得分:12)
为什么需要在finally
块中执行此操作?由于try/catch
是一个表达式,因此您可以匹配其值:
try {
val w = runOrFailWithException("Please work...")
Right(w)
} catch {
case ex: Exception => Left(ex)
} match {
case Right(_) =>
case Left(_) =>
}