-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIO.scala
38 lines (32 loc) · 810 Bytes
/
IO.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package baovitt.io
import scala.util.control.NonFatal
// Defines all IO methods.
object IO:
// Takes a resource, a function on that resource, returns the
// result of that function alongside the resource, and
// safely closes the resource.
def withResourcesAutoclose[T <: AutoCloseable, V](
resource: T,
)( f: T => V ): V =
var exception: Throwable | Null = null
try
f(resource)
catch
case NonFatal(e) =>
exception = e
throw e
finally
closeAndAddSuppressed(exception, resource)
// Safely closes a resource with an exception.
private def closeAndAddSuppressed(
e: Throwable | Null,
resource: AutoCloseable
): Unit =
if (e != null)
try
resource.close()
catch
case NonFatal(suppressed) =>
e.nn.addSuppressed(suppressed)
else
resource.close()