33

我已经定义了“使用”功能如下:

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

9 回答 9

16

开始Scala 2.13,标准库提供了一个专用的资源管理实用程序:Using.

更具体地说,Using#Manager可以在处理多个资源时使用。

在我们的例子中,我们可以管理不同的资源,例如 yourPrintWriterBufferedReaderas they both implement 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(())
于 2019-03-31T12:24:19.823 回答
13

有人已经这样做了——它被称为Scala ARM

从自述文件:

import resource._
for(input <- managed(new FileInputStream("test.txt")) {
  // Code that uses the input as a FileInputStream
}
于 2011-10-13T03:07:23.290 回答
6

我一直在考虑这个问题,我想也许还有其他方法可以解决这个问题。这是我对支持“任意数量”参数的看法(受元组提供的限制):

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(不是双关语)更清晰,但这是一个有趣的谜题。

于 2010-03-08T08:33:00.020 回答
3

使用结构类型似乎有点矫枉过正,因为java.lang.AutoCloseable注定要使用:

  def using[A <: AutoCloseable, B](resource: A)(block: A => B): B =
    try block(resource) finally resource.close()

或者,如果您更喜欢扩展方法:

  implicit class UsingExtension[A <: AutoCloseable](val resource: A) extends AnyVal {
    def using[B](block: A => B): B = try block(resource) finally resource.close()
  }

using2 是可能的:

  def using2[R1 <: AutoCloseable, R2 <: AutoCloseable, B](resource1: R1, resource2: R2)(block: (R1, R2) => B): B =
    using(resource1) { _ =>
      using(resource2) { _ =>
        block(resource1, resource2)
      }
    }

但恕我直言很丑 - 我宁愿简单地将这些 using 语句嵌套在客户端代码中。

于 2018-05-23T23:40:03.857 回答
2

不幸的是,标准 Scala 中不支持任意类型的任意长度参数列表。

您可以通过一些语言更改来执行类似的操作(以允许可变参数列表作为 HLists 传递;请参阅此处了解所需内容的大约 1/3)。

现在,最好的办法就是做 Tuple 和 Function 所做的事情:根据需要为尽可能多的 N 实现 usingN。

当然,两个很容易:

def using2[A, B <: {def close(): Unit}, C <: { def close(): Unit}](closeB: B, closeC: C)(f: (B,C) => A): A = {
  try { f(closeB,closeC) } finally { closeB.close(); closeC.close() }
}

如果您需要更多,可能值得编写一些可以生成源代码的东西。

于 2010-03-07T14:04:35.370 回答
2

这是一个示例,它允许您将 scala 用于理解作为 java.io.Closeable 的任何项目的自动资源管理块,但它可以很容易地扩展为适用于具有 close 方法的任何对象。

这种用法似乎非常接近 using 语句,并且允许您轻松地在一个块中定义任意数量的资源。

object ResourceTest{
  import CloseableResource._
  import java.io._

  def test(){
    for( input <- new BufferedReader(new FileReader("/tmp/input.txt")); output <- new FileWriter("/tmp/output.txt") ){
      output.write(input.readLine)
    }
  }
}

class CloseableResource[T](resource: =>T,onClose: T=>Unit){
  def foreach(f: T=>Unit){
    val r = resource
    try{
      f(r)
    }
    finally{
      try{
        onClose(r)
      }
      catch{
        case e =>
          println("error closing resource")
          e.printStackTrace
      }
    }
  }
}

object CloseableResource{
  implicit def javaCloseableToCloseableResource[T <: java.io.Closeable](resource:T):CloseableResource[T] = new CloseableResource[T](resource,{_.close})
}
于 2010-03-10T20:23:58.503 回答
2

从程序路径中分离清理算法是个好主意。

此解决方案可让您在范围内累积可关闭对象。
范围清理将在块执行后进行,或者可以分离范围。然后可以稍后进行范围的清洁。

通过这种方式,我们获得了同样的便利,而不受限于单线程编程。

实用程序类:

import java.io.Closeable

object ManagedScope {
  val scope=new ThreadLocal[Scope]();
  def managedScope[T](inner: =>T):T={
    val previous=scope.get();
    val thisScope=new Scope();
    scope.set(thisScope);
    try{
      inner
    } finally {
      scope.set(previous);
      if(!thisScope.detatched) thisScope.close();
    }
  }

  def closeLater[T <: Closeable](what:T): T = {
    val theScope=scope.get();
    if(!(theScope eq null)){
      theScope.closeables=theScope.closeables.:+(what);
    }
    what;
  }

  def detatchScope(): Scope={
    val theScope=scope.get();
    if(theScope eq null) null;
    else {
      theScope.detatched=true;
      theScope;
    }
  }
}

class Scope{
  var detatched=false;
  var closeables:List[Closeable]=List();

  def close():Unit={
    for(c<-closeables){
      try{
        if(!(c eq null))c.close();
      } catch{
        case e:Throwable=>{};
      }
    }
  }
}

用法:

  def checkSocketConnect(host:String, portNumber:Int):Unit = managedScope {
    // The close later function tags the closeable to be closed later
    val socket = closeLater( new Socket(host, portNumber) );
    doWork(socket);
  }

  def checkFutureConnect(host:String, portNumber:Int):Unit = managedScope {
    // The close later function tags the closeable to be closed later
    val socket = closeLater( new Socket(host, portNumber) );
    val future:Future[Boolean]=doAsyncWork(socket);

    // Detatch the scope and use it in the future.
    val scope=detatchScope();
    future.onComplete(v=>scope.close());
  }
于 2015-10-13T15:11:12.750 回答
1

这个解决方案没有你想要的语法,但我认为它足够接近:)

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

using(List(new BufferedReader(new FileReader("in.txt")), new PrintWriter("out.txt"))) {
  case List(in: BufferedReader, out: PrintWriter) => out.println(in.readLine())
}

当然,不利的一面是您必须在 using 块中BufferedReader输入类型。PrintWrter您也许可以添加一些魔法,以便您只需要在使用类型 A 时List(in, out)使用 多个 ORed 类型边界

通过定义一些非常hacky和危险的隐式转换,您可以避免必须键入List(以及另一种绕过指定资源类型的方法),但我没有记录细节,因为它太危险了IMO。

于 2013-11-23T12:43:58.677 回答
1

这是我对 Scala 资源管理的解决方案:

  def withResources[T <: AutoCloseable, V](r: => T)(f: T => V): V = {
    val resource: T = r
    require(resource != null, "resource is null")
    var exception: Throwable = null
    try {
      f(resource)
    } catch {
      case NonFatal(e) =>
        exception = e
        throw e
    } finally {
      closeAndAddSuppressed(exception, resource)
    }
  }

  private def closeAndAddSuppressed(e: Throwable,
                                    resource: AutoCloseable): Unit = {
    if (e != null) {
      try {
        resource.close()
      } catch {
        case NonFatal(suppressed) =>
          e.addSuppressed(suppressed)
      }
    } else {
      resource.close()
    }
  }

我在多个 Scala 应用程序中使用了它,包括在 Spark 执行器中管理资源。并且应该知道,我们还有其他更好的方法来管理资源,例如 CatsIO:https ://typelevel.org/cats-effect/datatypes/resource.html 。如果你对 Scala 中的纯 FP 没问题。

要回答您的最后一个问题,您绝对可以像这样嵌套资源:

withResource(r: File)(
  r => {
    withResource(a: File)(
      anotherR => {
        withResource(...)(...)
      }
    )
  }
)

这样,不仅可以保护这些资源免于泄漏,它们还将以正确的顺序(如堆栈)释放。与 CatsIO 的 Resource Monad 相同的行为。

于 2019-03-22T19:50:40.137 回答