Take the 2-minute tour ×

Java 7 has introduced automatic resource management:

  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(...) { }?

share|improve this question
I think the [scala-language] mailing list would be a better place to ask this question. –  missingfaktor Sep 16 '11 at 11:30
I think if it was added, then not as a language feature but as part of the std lib. –  ziggystar Sep 16 '11 at 11:31
There won't be any language level feature added as it's easily doable using the existing language features, as per the answers below. –  sourcedelica Sep 16 '11 at 11:52
I guess I should amend my question to ask if there is any plan to add the pattern to the standard library. It really does not matter to me whether it is a part of the language or standard library, as long as it's available without using an outside resource. It seems silly to write a 1-page utility that has 37 Maven dependencies :-). –  Ralph Sep 16 '11 at 12:50
I should really start using that. I missed C#'s Disposable pattern for ages now. –  ripper234 Nov 20 '11 at 23:40
add comment

3 Answers

up vote 12 down vote accepted

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) {

Monadic style

val first_ten_bytes = managed(new FileInputStream("test.txt")) map { 
   input =>
     val buffer = new Array[Byte](10)

On the github page are some more examples

share|improve this answer
add comment

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:



You can even make a more generic loaner by doing something like:

What are your most useful own library extensions?

share|improve this answer
+1 for Alois :) –  Thomas Jungblut Sep 16 '11 at 11:49
hehe Thomas ;) ... @Ralph I've just added a link to JPPellet example which is very generic –  Alois Cochard Sep 16 '11 at 12:23
add comment

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.

share|improve this answer
add comment

Your Answer


