Sunday, November 6, 2011

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.
def using[T <: { def close()}, R] (resource: T) (block: T => R) = {
  try     block(resource)
  finally resource.close
An example usage :

using(new PrintStream("/tmp/dummy")) { o =>
  o.print("Hello world")

No comments:

Post a Comment