gpt4 book ai didi

scala - 在 try/catch block 中最终是 "out of scope"

转载 作者:行者123 更新时间:2023-12-04 10:42:20 27 4
gpt4 key购买 nike

有没有办法访问在 finally 块中的 try/catch 块中创建的 val ?或者是超出范围的 finally 块。

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(_) =>
}

关于scala - 在 try/catch block 中最终是 "out of scope",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9483026/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com