- Learn Scala Programming
- Slava Schmidt
- 389字
- 2021-06-10 19:35:40
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 9, Familiarizing 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 6, Exploring 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 Classes. Using 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.13—the new collection library.
- Go Web編程
- Mastering NetBeans
- Testing with JUnit
- C語言程序設(shè)計(jì)(第3版)
- SQL for Data Analytics
- 微服務(wù)設(shè)計(jì)原理與架構(gòu)
- Elasticsearch Server(Third Edition)
- 深入淺出Serverless:技術(shù)原理與應(yīng)用實(shí)踐
- Learning OpenStack Networking(Neutron)
- Learning Hadoop 2
- Mastering Android Studio 3
- ASP.NET Core and Angular 2
- Python深度學(xué)習(xí)(第2版)
- Practical Responsive Typography
- Android 5從入門到精通