"using" function

Albert Cenkier picture Albert Cenkier · Mar 7, 2010 · Viewed 19.7k times · Source

I've defined 'using' function as following:

def using[A, B <: {def close(): Unit}] (closeable: B) (f: B => A): A =
  try { f(closeable) } finally { closeable.close() }

I can use it like that:

using(new PrintWriter("sample.txt")){ out =>
  out.println("hellow world!")
}

now I'm curious how to define 'using' function to take any number of parameters, and be able to access them separately:

using(new BufferedReader(new FileReader("in.txt")), new PrintWriter("out.txt")){ (in, out) =>
  out.println(in.readLIne)
}

Answer

Lambda Fairy picture Lambda Fairy · Oct 13, 2011

Someone has already done this—it's called Scala ARM.

From the readme:

import resource._
for(input <- managed(new FileInputStream("test.txt")) {
  // Code that uses the input as a FileInputStream
}