Search code examples
scalaresource-management

What Automatic Resource Management alternatives exist for Scala?


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 another. I did see a pretty cool example using continuations, though.

At any rate, a lot of that code has flaws of one type or another, so I figured it would be a good idea to have a reference here on Stack Overflow, where we can vote up the most correct and appropriate versions.


Solution

  • 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.