Disposable Resource Pattern

三世轮回 提交于 2019-12-03 13:32:48
vossad01

At this time you will need to look to the Scala ARM for a common implementation. Though, as you mentioned, it is a separate library.

For more information:

This answer at functional try & catch w/ Scala links to the Loan Pattern on the scala wiki which has code samples. (I am not re-posting the link because link is subject to change)

Using a variable in finally block has a few answers showing ways you could write your own.

Starting Scala 2.13, the standard library provides a dedicated resource management utility: Using.

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")

Note that you can place the implicit releasable in the companion object of Resource for clarity.


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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!