What Automatic Resource Management alternatives exist for Scala?

后端 未结 9 1386
半阙折子戏
半阙折子戏 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:41

    For now Scala 2.13 has finally supported: try with resources by using Using :), Example:

    val lines: Try[Seq[String]] =
      Using(new BufferedReader(new FileReader("file.txt"))) { reader =>
        Iterator.unfold(())(_ => Option(reader.readLine()).map(_ -> ())).toList
      }
    

    or using Using.resource avoid Try

    val lines: Seq[String] =
      Using.resource(new BufferedReader(new FileReader("file.txt"))) { reader =>
        Iterator.unfold(())(_ => Option(reader.readLine()).map(_ -> ())).toList
      }
    

    You can find more examples from Using doc.

    A utility for performing automatic resource management. It can be used to perform an operation using resources, after which it releases the resources in reverse order of their creation.

提交回复
热议问题