是否有方法访问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(_) =>
}
}
}
为什么需要在finally
块中执行此操作?由于try/catch
是一个表达式,因此可以匹配其值:
try {
val w = runOrFailWithException("Please work...")
Right(w)
} catch {
case ex: Exception => Left(ex)
} match {
case Right(_) =>
case Left(_) =>
}