1. Overview

In Java, we can use the try-with-resources statement to automatically close all resources that we need in our code. This statement works with every class that implements the AutoCloseable interface.

Unfortunately, such a feature does not exist in Scala. This article shows two methods of getting the same result in Scala.

2. Try-With-Resources in Java

When we write a Java program that, for example, reads data from a file, we need to create an instance of the class that holds the filehandle.

When we no longer need the file, we must release the handle:

try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
    return reader.readLine();
}

The try-with-resources statement produces the equivalent of writing:

BufferedReader reader = new BufferedReader(new FileReader(filePath));
try {
    return reader.readLine();
} finally {
    if (reader != null) {
        reader.close();
   } 
}

3. Using and Using.Manager in Scala

Since Scala 2.13, we can use the Using class, which provides support for automatic resource management in Scala.

First, we have to import it from the scala.util package:

import scala.util.Using

Now, we can pass the resource class as the parameter of the Using object and use that resource inside the function block:

Using(new BufferedReader(new FileReader(filePath))) { reader =>
  reader.readLine()
}

To achieve the same result when we need to close multiple resources, we must replace the Using class with Using.Manager.

It gives us an additional use function that turns a resource into an automatically managed resource:

Using.Manager { use =>
  val reader = use(new BufferedReader(new FileReader(filePath)))
  val anotherReader = use(new BufferedReader(new FileReader(otherFilePath)))

  reader.readLine()
  anotherReader.readLine()
}

4. Conclusion

In this article, we’ve described how to use the built-in Scala classes to automatically manage resources in a way similar to the Java try-with-resources statement.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.