Scala 有哪些自动资源管理替代方案? [英] What Automatic Resource Management alternatives exist for Scala?
问题描述
我在网上看到了很多 Scala 的 ARM(自动资源管理)示例.写一个似乎是一种仪式,尽管大多数看起来都非常相似.不过,我确实看到了一个使用延续的很酷的例子.
I have seen many examples of ARM (automatic resource management) on the web for Scala. It seems to be a rite-of-passage to write one, though most look pretty much like one another. I did see a pretty cool example using continuations, though.
无论如何,很多代码都有一种或另一种类型的缺陷,所以我认为在 Stack Overflow 上有一个参考是个好主意,我们可以在那里投票选出最正确和最合适的版本.
At any rate, a lot of that code has flaws of one type or another, so I figured it would be a good idea to have a reference here on Stack Overflow, where we can vote up the most correct and appropriate versions.
推荐答案
暂时 Scala 2.13 终于支持:try with resources
使用 使用 :),示例:
For now Scala 2.13 has finally supported: try with resources
by using Using :), Example:
val lines: Try[Seq[String]] =
Using(new BufferedReader(new FileReader("file.txt"))) { reader =>
Iterator.unfold(())(_ => Option(reader.readLine()).map(_ -> ())).toList
}
或使用 Using.resource
避免 Try
val lines: Seq[String] =
Using.resource(new BufferedReader(new FileReader("file.txt"))) { reader =>
Iterator.unfold(())(_ => Option(reader.readLine()).map(_ -> ())).toList
}
您可以从 使用 文档.
用于执行自动资源管理的实用程序.它可用于执行使用资源的操作,然后以与创建资源相反的顺序释放资源.
A utility for performing automatic resource management. It can be used to perform an operation using resources, after which it releases the resources in reverse order of their creation.
这篇关于Scala 有哪些自动资源管理替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!