-
Notifications
You must be signed in to change notification settings - Fork 50
Basic Usage
The Scala ARM library provides three “modes” of operations:
- Imperative style resource management functions.
- A monadic style resource management class.
- A delimited continuation style API.
The Scala ARM library allows users to ensure opening closing of resources within blocks of code using the managed method. This is easiest to accomplish with a for expression and the managed method defined on scala.resource:
import resource._
for(input <- managed(new FileInputStream("test.txt")) {
// Code that uses the input as a FileInputStream
}
This style of usage will ensure that the file input stream is closed at the end of the for expression. In the event of an exception, the originating exception (from inside the for block) will be thrown and any exceptions thrown while closing the resource will be suppressed. The benefits of using for expressions is that multiple resources can be managed together. For example, one can do the following:
import resource._
// Copy input into output.
for(input <- managed(new java.io.FileInputStream("test.txt");
output <- managed(new java.io.FileOutputStream("test2.txt")) {
val buffer = new Array[Byte](512)
while(input.read(buffer) != -1) {
output.write(buffer);
}
}
There is a convenience notation for those who don’t like using for comprehensions:
import resource._
managed(DriverManager.getConnection(url, username, password)) { connection =>
// Something that uses connection
}