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

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

主站蜘蛛池模板: 襄垣县| 长海县| 新竹县| 湄潭县| 磐安县| 英吉沙县| 张家口市| 万盛区| 淮滨县| 达孜县| 海南省| 长治县| 万州区| 海城市| 嘉荫县| 新津县| 安图县| 巫溪县| 康乐县| 华宁县| 汪清县| 定远县| 资溪县| 宁远县| 基隆市| 黔南| 台州市| 崇义县| 龙岩市| 固阳县| 北安市| 陵水| 新源县| 巨鹿县| 崇礼县| 富川| 苏尼特左旗| 内黄县| 芜湖市| 泊头市| 香格里拉县|