Skip to content

Commit 0a71760

Browse files
committed
Include implicit Manager example in Using doc
1 parent a7443ea commit 0a71760

File tree

1 file changed

+38
-5
lines changed

1 file changed

+38
-5
lines changed

library/src/scala/util/Using.scala

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,20 +44,53 @@ import scala.util.control.{ControlThrowable, NonFatal}
4444
* import java.io.{BufferedReader, FileReader}
4545
* import scala.util.{Try, Using}
4646
*
47+
* val files = List("file1.txt", "file2.txt", "file3.txt", "file4.txt")
4748
* 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)))
5251
*
5352
* // use your resources here
5453
* def lines(reader: BufferedReader): Iterator[String] =
5554
* Iterator.continually(reader.readLine()).takeWhile(_ != null)
5655
*
57-
* (lines(r1) ++ lines(r2) ++ lines(r3) ++ lines(r4)).toList
56+
* files.map(reader).flatMap(lines)
5857
* }
5958
* }}}
6059
*
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+
*
6194
* If you wish to avoid wrapping management and operations in a `Try`, you can use
6295
* [[Using.resource `Using.resource`]], which throws any exceptions that occur.
6396
*

0 commit comments

Comments
 (0)