Automatic Resource Management

Scala 2.13 adds a practical way to automatically manage resources. We will discuss other ways to manage resources and implement dependency-injection in Chapter 9Familiarizing Yourself with Basic Monads and 10. scala.util.Using allows us to do this in a familiar side-effecting way. All operations on the resource are wrapped in a Try, which we'll talk about in Chapter 6Exploring Built-In Effects. If Exceptions is thrown, the first one is returned within a Try. The exception-handling is quite sophisticated in some corner cases and we invite the reader to consult ScalaDoc for a detailed description of it. 

Using is a class that takes some resources as a by-name parameter. The resource can be anything that has a type class instance for scala.util.Resource available. Such an instance for java.lang.AutoCloseable is provided in the standard library. We will study type classes in Chapter 4, Getting to Know Implicits and Type ClassesUsing also has a monadic interface, which allows us to combine multiple resources in for-comprehensions. We'll discuss monads in Chapter 9, Familiarizing Yourself with Basic Monads.

Here is an example of the practical application of Using. We will define a resource that implements AutoCloseable and a few of these resources in for-comprehension as a source of the data:

scala> import scala.util.{Try, Using}
import scala.util.{Try, Using}
scala> final case class Resource(name: String) extends AutoCloseable {
| override def close(): Unit = println(s"Closing $name")
| def lines = List(s"$name line 1", s"$name line 2")
| }
defined class Resource
scala> val List(r1, r2, r3) = List("first", "2", "3").map(Resource)
r1: Resource = Resource(first)
r2: Resource = Resource(2)
r3: Resource = Resource(3)

scala> val lines: Try[Seq[String]] = for {
| u1 <- Using(r1)
| u2 <- Using(r2)
| u3 <- Using(r3)
| } yield {
| u1.lines ++ u2.lines ++ u3.lines
| }
Closing 3
Closing 2
Closing first
lines: scala.util.Try[Seq[String]] = Success(List(first line 1, first line 2, 2 line 1, 2 line 2, 3 line 1, 3 line 2))

The output in the console demonstrates that the result contains lines from all of the resources, and the resources themselves are automatically closed in the reverse order.

Now, after this small warm-up, we are ready to dive into the foundation of version 2.13the new collection library.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.199.122