一次性资源模式 [英] Disposable Resource Pattern
问题描述
Scala 库中是否有任何标准化的内容来支持一次性资源模式?
Is there anything standardized within the Scala library to support the disposable resource pattern?
我的意思是类似于 C# 和 .NET 支持的内容,仅举一个.
I mean something similar to that supported by C# and .NET just to mention one.
例如,官方 Scala 库是否提供了这样的东西:
For example does official Scala library provide something like this:
trait Disposable { def dispose() }
class Resource extends Disposable
using (new Resource) { r =>
}
注意:我知道这篇文章«Scala finally 块关闭/刷新资源» 但它似乎没有集成在标准库中
Note: I'm aware of this article «Scala finally block closing/flushing resource» but it seems not integrated within the standard lib
推荐答案
从 Scala 2.13
开始,标准库提供了专用的资源管理实用程序:使用
.
Starting Scala 2.13
, the standard library provides a dedicated resource management utility: Using
.
您只需要使用 Releasable
特性:
You will just have to provide an implicit definition of how to release the resource, using the Releasable
trait:
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
的伴随对象中.
Note that you can place the implicit releasable in the companion object of Resource
for clarity.
请注意,您也可以使用 Java 的 AutoCloseable
而不是 Using.Releasable
,因此任何实现 AutoCloseable
的 Java 或 Scala 对象(例如 scala.io.Source
或 java.io.PrintWriter
) 可以直接与 Using
一起使用:
Note that you can also use Java's AutoCloseable
instead of Using.Releasable
and thus any Java or Scala object implementing AutoCloseable
(such as scala.io.Source
or java.io.PrintWriter
) can directly be used with 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")
这篇关于一次性资源模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!