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