Automatic resource liberation
It is very easy to implements automatic resource liberation in Scala, thanks to parametric type which can be use without giving a specific class but rather any class which implements the given method signature !
In our case, we define a method which accepts all classes with a close method.
In our case, we define a method which accepts all classes with a close method.
An example usage :
def using[T <: { def close()}, R] (resource: T) (block: T => R) = {
try block(resource)
finally resource.close
}
import java.io._
using(new PrintStream("/tmp/dummy")) { o =>
o.print("Hello world")
}