java7新增了try-with-resources的功能,在使用需要关闭的流对象时,可以很方便的实现自动关闭IO,但是scala没有这种功能,不过我们可以通过自定义方法的方式实现类似功能。

//通过泛型实现,接收AutoCloseable的子类,调用AutoCloseable的close方法
def using[A <: AutoCloseable, B](a: A)(f: A => B) = {
  try f(a)
  finally if (a != null) a.close()
}

//通过反射实现,接收带有close方法的类,通过反射调用close方法
def using[A <: {def close(): Unit}, B](a: A)(f: A => B): B = {
  try f(a)
  finally if (a != null) a.close()
}

使用方式:

using(new FileWriter(filePath))(_.write(content))