“使用"功能 [英] "using" function

查看:54
本文介绍了“使用"功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将使用"函数定义如下:

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() }

我可以这样使用它:

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)
}

推荐答案

已经有人这样做了—它叫做 Scala ARM.

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

来自自述文件:

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

这篇关于“使用"功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆