-->

一次性资源模式(Disposable Resource Pattern)

2019-08-17 18:51发布

有什么Scala库中的标准化,支持一次性资源模式

我的意思是类似的C#和.NET支持刚才提到一个东西。

例如没有正式Scala库提供的东西是这样的:

trait Disposable { def dispose() }

class Resource extends Disposable

using (new Resource) { r =>

}

注:我知道这篇文章«的斯卡拉finally块关闭/冲洗资源 »但似乎不是标准库中集成

Answer 1:

这时,你需要寻找到斯卡拉ARM为共同实施。 不过,正如你提到的,它是一个独立的库。

欲获得更多信息:

这个答案在功能的尝试和捕捉W /斯卡拉链接到在具有代码样本中阶维基贷款模式。 (我不是重新张贴链接,因为链接可随时更改)

在finally块中使用的变量有几个答案显示方式,你可以写你自己的。



Answer 2:

开始Scala 2.13 ,标准库提供了一个专门的资源管理工具: Using

你只需要提供如何释放资源,采用隐式定义Releasable特点:

import scala.util.Using
import scala.util.Using.Releasable

case class Resource(field: String)

implicit val releasable: Releasable[Resource] = resource => println(s"closing $resource")

Using(Resource("hello world")) { resource => resource.field.toInt }
// closing Resource(hello world)
// res0: scala.util.Try[Int] = Failure(java.lang.NumberFormatException: For input string: "hello world")

请注意,您可以将隐性释放中的同伴对象Resource的清晰度。


请注意,您还可以使用Java的AutoCloseable代替Using.Releasable ,从而实现任何Java或Scala的对象AutoCloseable (如scala.io.Sourcejava.io.PrintWriter ),可直接与使用Using

import scala.util.Using

case class Resource(field: String) extends AutoCloseable {
  def close(): Unit = println(s"closing $this")
}

Using(Resource("hello world")) { resource => resource.field.toInt }
// closing Resource(hello world)
// res0: scala.util.Try[Int] = Failure(java.lang.NumberFormatException: For input string: "hello world")


文章来源: Disposable Resource Pattern