我在使用 PDF 库时遇到了这个问题,但在很多其他场合我也会有这样有用的东西。
在很多情况下,您拥有资源(需要关闭)并且您使用这些资源来获取仅在资源打开且尚未释放时才有效的对象。
假设b
下面代码中的引用仅在 a 打开时有效:
val a = open()
try {
val b = a.someObject()
} finally {
a.close()
}
现在,这段代码很好,但这段代码不是:
val b = {
val a = open()
try {
a.someObject()
} finally {
a.close()
}
}
使用该代码,我将引用资源 a 的某些内容,而 a 不再打开。
理想情况下,我想要这样的东西:
// Nothing producing an instance of A yet, but just capturing the way A needs
// to be opened.
a = Safe(open()) // Safe[A]
// Just building a function that opens a and extracts b, returning a Safe[B]
val b = a.map(_.someObject()) // Safe[B]
// Shouldn't compile since B is not safe to extract without being in the scope
// of an open A.
b.extract
// The c variable will hold something that is able to exist outside the scope of
// an open A.
val c = b.map(_.toString)
// So this should compile
c.extract