如何在Scala中进行for-understandingnce中最好地处理带有副作用的函数?
我有一个理解,通过调用函数f1创建一种资源(x)开始.这个资源有一个close -method需要在结束时调用,但是如果for-comprehension以某种方式失败(除非.
所以我们有类似的东西:
import scala.util.{Try,Success,Failure}
trait Resource {
def close() : Unit
}
// Opens some resource and returns it as Success or returns Failure
def f1 : Try[Resource] = ...
def f2 : Try[Resource] = ...
val res = for {
x <- f1
y <- f2
} yield {
(x,y)
}
Run Code Online (Sandbox Code Playgroud)
我应该在哪里调用close方法?我可以在for-comprehension结束时将其称为最后一个语句(z < - x.close),在yield-part中,或在for-comprehension之后(res._1.close).它们都不能确保在发生错误时调用close(例如,如果f2失败).或者,我可以分开
x <- f1
Run Code Online (Sandbox Code Playgroud)
出于这样的理解:
val res = f1
res match {
case Success(x) …Run Code Online (Sandbox Code Playgroud) scala ×1