Is there a more idiomatic way of opening a resource in Scala and applying methods to it than this method (translated directly from java):
var is: FileInputSt
Starting Scala 2.13, the standard library provides a dedicated resource management utility: Using.
It can be used in this case with FileInputStream as it implements AutoCloseable in order to play with an input file and, no matter what, close the file resource afterwards:
import scala.util.{Using, Failure}
import java.io.FileInputStream
Using(new FileInputStream(in)) {
is => func(is)
}.recoverWith {
case e: java.io.IOException =>
println("Error: could not open file.")
Failure(e)
}
Since Using produces a Try providing either the result of the operation or an error, we can work with the exception via Try#recoverWith.