开发者

Java 7 style automatic resource management for Scala

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.

开发者_JAVA技巧

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


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.


There is light-weight (10 lines of code) ARM included with better-files. See: https://github.com/pathikrit/better-files#lightweight-arm

import better.files._
for {
  in <- inputStream.autoClosed
  out <- outputStream.autoClosed
} in.pipeTo(out)
// The input and output streams are auto-closed once out of scope
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜