官术网_书友最值得收藏!

  • 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 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.

主站蜘蛛池模板: 台州市| 建平县| 张北县| 连城县| 井陉县| 绥江县| 潢川县| 凌源市| 稷山县| 宾阳县| 石嘴山市| 遂溪县| 辽阳市| 盐亭县| 阳曲县| 石门县| 社旗县| 莒南县| 玉山县| 仪征市| 长乐市| 龙海市| 朔州市| 云梦县| 邯郸县| 霸州市| 英吉沙县| 盐津县| 石屏县| 夏邑县| 弥渡县| 五常市| 东台市| 定安县| 菏泽市| 南汇区| 安福县| 莫力| 韶关市| 朔州市| 凤城市|