【发布时间】:2015-11-27 20:07:09
【问题描述】:
如何在 Scala 的 for-comprehensions 中最好地处理具有副作用的函数?
我有一个 for 理解,它首先通过调用函数 f1 创建一种资源 (x)。该资源有一个 close 方法,需要在最后调用,但如果理解以某种方式失败(除非。
所以我们有类似的东西:
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)
}
我应该在哪里调用 close 方法?我可以在 for-comprehension 的末尾将其称为最后一条语句 (z f2 失败),它们都不能确保调用 close。 或者,我可以分开
x <- f1
不理解是这样的:
val res = f1
res match {
case Success(x) => {
for {
y <- f2
}
x.close
}
case Failure(e) => ...
:
这将确保调用 close 但不是很好的代码。 难道没有更聪明、更干净的方法来实现同样的目标吗?
【问题讨论】:
标签: scala