What Automatic Resource Management alternatives exist for Scala?

后端 未结 9 1380
半阙折子戏
半阙折子戏 2020-12-02 03:57

I have seen many examples of ARM (automatic resource management) on the web for Scala. It seems to be a rite-of-passage to write one, though most look pretty much like one a

9条回答
  •  温柔的废话
    2020-12-02 04:20

    Here is @chengpohi's answer, modified so it works with Scala 2.8+, instead of just Scala 2.13 (yes, it works with Scala 2.13 also):

    def unfold[A, S](start: S)(op: S => Option[(A, S)]): List[A] =
      Iterator
        .iterate(op(start))(_.flatMap{ case (_, s) => op(s) })
        .map(_.map(_._1))
        .takeWhile(_.isDefined)
        .flatten
        .toList
    
    def using[A <: AutoCloseable, B](resource: A)
                                    (block: A => B): B =
      try block(resource) finally resource.close()
    
    val lines: Seq[String] =
      using(new BufferedReader(new FileReader("file.txt"))) { reader =>
        unfold(())(_ => Option(reader.readLine()).map(_ -> ())).toList
      }
    

提交回复
热议问题