@@ -44,20 +44,53 @@ import scala.util.control.{ControlThrowable, NonFatal}
44
44
* import java.io.{BufferedReader, FileReader}
45
45
* import scala.util.{Try, Using}
46
46
*
47
+ * val files = List("file1.txt", "file2.txt", "file3.txt", "file4.txt")
47
48
* val lines: Try[Seq[String]] = Using.Manager { use =>
48
- * val r1 = use(new BufferedReader(new FileReader("file1.txt")))
49
- * val r2 = use(new BufferedReader(new FileReader("file2.txt")))
50
- * val r3 = use(new BufferedReader(new FileReader("file3.txt")))
51
- * val r4 = use(new BufferedReader(new FileReader("file4.txt")))
49
+ * // acquire resources
50
+ * def reader(filename: String) = use(new BufferedReader(new FileReader(filename)))
52
51
*
53
52
* // use your resources here
54
53
* def lines(reader: BufferedReader): Iterator[String] =
55
54
* Iterator.continually(reader.readLine()).takeWhile(_ != null)
56
55
*
57
- * (lines(r1) ++ lines(r2) ++ lines(r3) ++ lines(r4)).toList
56
+ * files.map(reader).flatMap( lines)
58
57
* }
59
58
* }}}
60
59
*
60
+ * Composed or "wrapped" resources may be acquired in order of construction,
61
+ * if "underlying" resources are not closed:
62
+ * {{{
63
+ * def reader(filename: String) = use(new BufferedReader(use(new FileReader(filename))))
64
+ * }}}
65
+ *
66
+ * Custom resources can be registered on construction by requiring an implicit `Manager`.
67
+ * This ensures they will be released even if composition fails:
68
+ * {{{
69
+ * import scala.util.Using
70
+ *
71
+ * case class X(x: String)(implicit mgr: Using.Manager) extends AutoCloseable {
72
+ * override def close() = println(s"CLOSE $x")
73
+ * mgr.acquire(this)
74
+ * }
75
+ * case class Y(y: String)(x: String)(implicit mgr: Using.Manager) extends AutoCloseable {
76
+ * val xres = X(x)
77
+ * override def close() = println(s"CLOSE $y")
78
+ * // an error during construction releases previously acquired resources
79
+ * assert(y != null, "y is null")
80
+ * mgr.acquire(this)
81
+ * }
82
+ *
83
+ * Using.Manager { implicit mgr =>
84
+ * val y = Y("Y")("X")
85
+ * println(s"USE $y")
86
+ * }
87
+ * println {
88
+ * Using.Manager { implicit mgr =>
89
+ * Y(null)("X")
90
+ * }
91
+ * } // Failure(java.lang.AssertionError: assertion failed: y is null)
92
+ * }}}
93
+ *
61
94
* If you wish to avoid wrapping management and operations in a `Try`, you can use
62
95
* [[Using.resource `Using.resource` ]], which throws any exceptions that occur.
63
96
*
0 commit comments