Java 7 has introduced automatic resource management:
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
This will work with any class that implements java.lang.AutoClosable
.
I know there are several examples of doing automatic resource management in Scala, including one demonstrated by Martin Odersky.
Is there any plan to add a language-level resource management to Scala, similar to Java's try(...) { }
?
automatic resource management or try-with-resources is a new exception handling mechanism that was introduced in Java 7, which automatically closes the resources used within the try-catch block.
Overview. In Java, we can use the try-with-resources statement to automatically close all resources that we need in our code. This statement works with every class that implements the AutoCloseable interface. Unfortunately, such a feature does not exist in Scala.
close() method on all resources initialized in the try block. Important Points: The finally blocks were used to clean up the resources before Java 7. After java 7, resource cleanup is done automatically.
The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement.
In scala this can be added as a library. As a example scala-arm (https://github.com/jsuereth/scala-arm) from jsuereth:
Imperative Style:
// 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);
}
}
Monadic style
val first_ten_bytes = managed(new FileInputStream("test.txt")) map {
input =>
val buffer = new Array[Byte](10)
input.read(buffer)
buffer
}
On the github page are some more examples
I'm not aware of any Trait specially designed for that in Scala, but here is an example using the loan pattern on Java Closable:
http://whileonefork.blogspot.com/2011/03/c-using-is-loan-pattern-in-scala.html
EDIT
You can even make a more generic loaner by doing something like:
https://stackoverflow.com/questions/5945904/what-are-your-most-useful-own-library-extensions/5946514#5946514
Scala specs are pretty thin, because almost everything that can be implemented via the standard library, is. Thus there is no real need of adding ARM in the language itself.
Until now, Scala as no real IO API (defaulting on Java IO API). It's probable that a future Scala IO API will include some form of ARM. For instance, scala-io has ARM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With