
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
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.
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();
}
}
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()
}
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.