19

C#有usingIDisposable接口。Java 7+ 具有与接口相同try的功能AutoCloseable。Scala 允许您选择自己的实现来解决这个问题。

scala-arm 似乎是流行的选择,由 Typesafe 的一名员工维护。但是,对于这样一个简单的行为,它似乎非常复杂。澄清一下,使用说明很简单,但了解所有代码在内部是如何工作的却相当复杂。

我刚刚写了以下超级简单的ARM解决方案:

object SimpleARM {
  def apply[T, Q](c: T {def close(): Unit})(f: (T) => Q): Q = {
    try {
      f(c)
    } finally {
      c.close()
    }
  }
}
  • 像简单手臂这样的东西有什么好处吗?似乎所有额外的复杂性都应该带来额外的好处。
  • 通常,最好使用其他人支持的公共开源库来实现通用行为,而不是使用自定义代码。
  • 任何人都可以推荐任何改进吗?
  • 这种简单的方法有什么限制吗?
4

9 回答 9

10

只要您不需要使用多个资源,所有资源都需要管理,您使用单一简单贷款模式的方法就可以正常工作。scala-arm monadic 方法允许这样做。

import resource.managed

managed(openResA).and(managed(openResB)) acquireFor { (a, b) => ??? }

val res = for {
  a <- managed(openResA)
  b <- managed(openResB)
  c <- managed(openResC)
} yield (a, b, c)

res acquireAndGet {
  case (a, b, c) => ???
}

scala-arm 中要了解的主要功能是resource.managedand .acquired{For,AndGet},顺便说一句,并不是很复杂。

于 2014-09-03T00:52:12.563 回答
6

这里是我较新的简单、一目了然的Scala ARM。这完全支持我能想到的每个用例,包括多个资源和收益值。这使用了一个非常简单的理解用法语法:

class AutoCloseableWrapper[A <: AutoCloseable](protected val c: A) {
  def map[B](f: (A) => B): B = {
    try {
      f(c)
    } finally {
      c.close()
    }
  }

  def foreach(f: (A) => Unit): Unit = map(f)

  // Not a proper flatMap.
  def flatMap[B](f: (A) => B): B = map(f)

  // Hack :)    
  def withFilter(f: (A) => Boolean) = this
}

object Arm {
  def apply[A <: AutoCloseable](c: A) = new AutoCloseableWrapper(c)
}

这是演示使用:

class DemoCloseable(val s: String) extends AutoCloseable {
  var closed = false
  println(s"DemoCloseable create ${s}")

  override def close(): Unit = {
    println(s"DemoCloseable close ${s} previously closed=${closed}")
    closed = true
  }
}

object DemoCloseable {
  def unapply(dc: DemoCloseable): Option[(String)] = Some(dc.s)
}

object Demo {
  def main(args: Array[String]): Unit = {
    for (v <- Arm(new DemoCloseable("abc"))) {
      println(s"Using closeable ${v.s}")
    }

    for (a <- Arm(new DemoCloseable("a123"));
         b <- Arm(new DemoCloseable("b123"));
         c <- Arm(new DemoCloseable("c123"))) {
      println(s"Using multiple resources for comprehension. a.s=${a.s}. b.s=${b.s}. c.s=${c.s}")
    }

    val yieldInt = for (v <- Arm(new DemoCloseable("abc"))) yield 123
    println(s"yieldInt = $yieldInt")

    val yieldString = for (DemoCloseable(s) <- Arm(new DemoCloseable("abc")); c <- s) yield c
    println(s"yieldString = $yieldString")

    println("done")
  }
}
于 2016-03-28T00:26:48.020 回答
3

这是我使用的代码:

def use[A <: { def close(): Unit }, B](resource: A)(code: A ⇒ B): B =
    try
        code(resource)
    finally
        resource.close()

与 Java try-with-resources 不同,资源不需要实现AutoCloseable。只close()需要一个方法。它只支持一种资源。

下面是一个与 an 一起使用的示例InputStream

val path = Paths get "/etc/myfile"
use(Files.newInputStream(path)) { inputStream ⇒
    val firstByte = inputStream.read()
    ....
}
于 2016-12-29T11:57:40.490 回答
1

http://illegalexception.schlichtherle.de/2012/07/19/try-with-resources-for-scala/

另一种实现,从“遵循 Java 规范”的角度来看可能更干净,但也不支持多种资源

于 2015-06-01T08:53:24.780 回答
1

这个非常适合我:

  implicit class ManagedCloseable[C <: AutoCloseable](resource: C) {
    def apply[T](block: (C) => T): T = {
    try {
      block(resource)
    } finally {
      resource.close()
    }
  }

例如在这个 Apache Cassandra 客户端代码中使用它:

val metadata = Cluster.builder().addContactPoint("vader").withPort(1234).build() { cluster =>
  cluster.getMetadata
}

甚至更短:

val metadata = Cluster.builder().addContactPoint("sedev01").withPort(9999).build()(_.getMetadata)
于 2017-08-08T19:59:15.023 回答
0

我可以推荐您建议的方法的改进,即:

  def autoClose[A <: AutoCloseable, B](resource: A)(code: A ⇒ B): B = {
    try
      code(resource)
    finally
      resource.close()
  }

是使用:

  def autoClose[A <: AutoCloseable, B](resource: A)(code: A ⇒ B): Try[B] = {
    val tryResult = Try {code(resource)}
    resource.close()
    tryResult
  }

恕我直言,拥有 tryResult 是一个Try[B],稍后将允许您更轻松的控制流程。

于 2017-08-28T12:19:57.993 回答
0

Choppy 的 Lazy TryClose monad 可能是您正在寻找的(披露:我是作者)。它与 Scala 的 Try 非常相似,但会自动关闭资源。

val ds = new JdbcDataSource()
val output = for {
  conn  <- TryClose(ds.getConnection())
  ps    <- TryClose(conn.prepareStatement("select * from MyTable"))
  rs    <- TryClose.wrap(ps.executeQuery())
} yield wrap(extractResult(rs))

// Note that Nothing will actually be done until 'resolve' is called
output.resolve match {
    case Success(result) => // Do something
    case Failure(e) =>      // Handle Stuff
}

有关更多信息,请参见此处:https ://github.com/choppythelumberjack/tryclose

于 2018-01-16T22:18:05.127 回答
0

这就是我的做法:

  def tryFinally[A, B](acquire: Try[A])(use: A => B)(release: A => Unit): Try[B] =
    for {
      resource <- acquire
      r = Try(use(resource)).fold(
        e => { release(resource); throw e },
        b => { release(resource); b }
      )
    } yield r

你可以调用.get它并让它返回B

于 2021-02-12T12:44:13.960 回答
0

这是在 Scala <= 2.12 中执行此操作的一种方法

trait SourceUtils {

  /**
    * Opens a `resource`, passes it to the given function `f`, then
    * closes the resource, returning the value returned from `f`.
    * 
    * Example usage:
    * {{{
    * val myString: String =
    *   using(scala.io.Source.fromFile("file.name")) { source =>
    *     source.getLines.mkString
    *   }
    * }}}
    * 
    * @param resource closeable resource to use, then close
    * @param f function which maps the resource to some return value
    * @tparam T type of the resource to be opened / closed
    * @tparam U type of the return value
    * @return the result of the function `f`
    */
  def using[T <: AutoCloseable, U](resource: => T)(f: T => U): U = {
    scala.util.Try(resource).fold(throw _, source => {
      val result = f(source)
      source.close()
      result
    })
  }
}
于 2021-11-08T11:47:21.467 回答