我已经定义了'使用'功能如下:
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!")
}
现在我很好奇如何定义'使用'函数来获取任意数量的参数,并且能够单独访问它们:
using(new BufferedReader(new FileReader("in.txt")), new PrintWriter("out.txt")){ (in, out) =>
  out.println(in.readLIne)
}
在许多示例中,描述了您可以使用scala.io.Source来读取整个文件,如下所示:
val str = scala.io.Source.fromFile("test.txt").mkString()
但没有提到关闭底层流.为什么Scala没有提供方便的方法来执行此操作,例如Python中的with子句?它看起来很有用但并不困难.
有没有其他更好的方法在Scala中安全地执行此操作,我的意思是读取整个文件?
在Scala应用程序中,我尝试使用java nio try-with-resource构造从文件中读取行.
Scala版本2.11.8 
Java版本1.8
try(Stream<String> stream = Files.lines(Paths.get("somefile.txt"))){
    stream.forEach(System.out::println); // will do business process here
}catch (IOException e) {
    e.printStackTrace(); // will handle failure case here
}  
但是编译器会抛出错误,例如
找不到:值流
◾尝试没有捕获或者最终等同于将其主体放入块中; 没有例外处理.
不确定是什么问题.我是使用Java NIO的新手,所以非常感谢任何帮助.
如何在Scala中进行for-understandingnce中最好地处理带有副作用的函数?
我有一个理解,通过调用函数f1创建一种资源(x)开始.这个资源有一个close -method需要在结束时调用,但是如果for-comprehension以某种方式失败(除非.
所以我们有类似的东西:
import scala.util.{Try,Success,Failure}
trait Resource {
  def close() : Unit
}
// Opens some resource and returns it as Success or returns Failure
def f1 : Try[Resource] = ...
def f2 : Try[Resource] = ...
val res = for {
  x <- f1
  y <- f2
} yield {
  (x,y)
}
我应该在哪里调用close方法?我可以在for-comprehension结束时将其称为最后一个语句(z < - x.close),在yield-part中,或在for-comprehension之后(res._1.close).它们都不能确保在发生错误时调用close(例如,如果f2失败).或者,我可以分开
x <- f1 
出于这样的理解:
val res = f1
res match {
  case Success(x) …