Scala 中的贷款人模式 [英] Loaner Pattern in Scala

查看:20
本文介绍了Scala 中的贷款人模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

深入 Scala 演示了贷款模式:

def readFile[T](f: File)(handler: FileInputStream => T): T = {
  val resource = new java.io.FileInputStream(f)
  try {
    handler(resource)
  } finally {
      resource.close()
  }
}

示例用法:

readFile(new java.io.File("test.txt")) { input =>
   println(input.readByte)
}

这段代码看起来简单明了.Scala 中 Loaner 模式的反模式"是什么,以便我知道如何避免它?

This code appears simple and clear. What is an "anti-pattern" of the Loaner pattern in Scala so that I know how to avoid it?

推荐答案

确保您计算的任何内容都得到及时评估,不再依赖于资源.Scala 使惰性计算变得相当容易.例如,如果您以这种方式包装 scala.io.Source.fromFile,您可以尝试

Make sure that whatever you compute is evaluated eagerly and no longer depends on the resource. Scala makes lazy computation fairly easy. For instance, if you wrap scala.io.Source.fromFile in this way, you might try

readFile("test.txt")(_.getLines)

不幸的是,这不起作用,因为 getLines 是惰性的(返回一个迭代器).Scala 没有任何很好的方法来表明哪些方法是惰性的,哪些不是.所以你只需要知道(文档往往会告诉你),并且你必须在返回之前实际完成工作:

Unfortunately, this doesn't work because getLines is lazy (returns an iterator). And Scala doesn't have any great way to indicate which methods are lazy and which are not. So you just have to know (docs will tend to tell you), and you have to actually do the work before returning:

readFile("test.txt")(_.getLines.toVector)

总的来说,这是一个非常有用的模式.只需确保在退出块之前对资源的所有访问都已完成(因此没有未完成的期货,没有依赖于资源的惰性值,没有迭代器,没有返回资源本身,没有尚未完全读取的流等.; 当然,如果它们不依赖于开放资源,而只依赖于基于资源的一些完全计算的数量,那么这些东西中的任何一个都可以).

Overall, it's a very useful pattern. Just make sure that all accesses to the resource are completed before exiting the block (so no uncompleted futures, no lazy vals that depend on the resource, no iterators, no returning the resource itself, no streams that haven't been fully read, etc.; of course any of these things are okay if they do not depend on the open resource but only on some fully-computed quantity based upon the resource).

这篇关于Scala 中的贷款人模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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