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