我将'using‘函数定义如下:
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‘函数来接受任意数量的参数,并且能够单独访问它们:
using(new BufferedReader(new FileReader("in.txt")), new PrintWriter("out.txt")){ (in, out) =>
out.println(in.readLIne)
}发布于 2019-03-31 20:24:20
从Scala 2.13开始,标准库提供了一个专用的资源管理实用程序:Using。
更具体地说,可以在处理多个资源时使用Using#Manager。
在我们的例子中,我们可以管理不同的资源,比如您的PrintWriter或BufferedReader,因为它们都实现了AutoCloseable,以便从一个文件读写到另一个文件,然后关闭输入和输出资源:
import scala.util.Using
import java.io.{PrintWriter, BufferedReader, FileReader}
Using.Manager { use =>
val in = use(new BufferedReader(new FileReader("input.txt")))
val out = use(new PrintWriter("output.txt"))
out.println(in.readLine)
}
// scala.util.Try[Unit] = Success(())发布于 2011-10-13 11:07:23
已经有人这么做了--这就是Scala ARM。
从自述文件中:
import resource._
for(input <- managed(new FileInputStream("test.txt")) {
// Code that uses the input as a FileInputStream
}发布于 2010-03-08 16:33:00
我一直在思考这个问题,我想也许还有其他方法来解决这个问题。下面是我对支持“任意数量”参数的看法(受限于元组提供的内容):
object UsingTest {
type Closeable = {def close():Unit }
final class CloseAfter[A<:Product](val x: A) {
def closeAfter[B](block: A=>B): B = {
try {
block(x);
} finally {
for (i <- 0 until x.productArity) {
x.productElement(i) match {
case c:Closeable => println("closing " + c); c.close()
case _ =>
}
}
}
}
}
implicit def any2CloseAfter[A<:Product](x: A): CloseAfter[A] =
new CloseAfter(x)
def main(args:Array[String]): Unit = {
import java.io._
(new BufferedReader(new FileReader("in.txt")),
new PrintWriter("out.txt"),
new PrintWriter("sample.txt")) closeAfter {case (in, out, other) =>
out.println(in.readLine)
other.println("hello world!")
}
}
}我想我是在重复使用这个库中已经编写了22个元组/产品类的事实……我不认为这种语法比使用嵌套using (不是双关语)更清楚,但这是一个有趣的难题。
https://stackoverflow.com/questions/2395984
复制相似问题