Search code examples
scala

scala Try: closing a file in failure scenario


I have written following code to write to a file:

Try {
       val filePath = "path/to/write/myfile.json"
       val file = new File(filePath)
       file.createNewFile();
       val fileWriter = new FileWriter(file)
       val objToWrite = someFunction()
       fileWriter.write(objToWrite.toJson)
       fileWriter.close()
     } match {
       case Failure(ex) =>
         log.error("Failed to save data")
         throw ex
       case Success(_) =>
         log.info("Data saved successfully")
    }

My question is does Try closes resource(file here) in case its a Failure?

If not, then how do we do it as finally block is not allowed with Try?

Also, can this IO operation be further improved as per scala best practises?


Solution

  • My question is does Try closes resource(file here) in case its a Failure?

    No. There's no resource management at all when using Try. It behaves like a "old school" Java try..catch without resource.

    If not, then how do we do it as finally block is not allowed with Try?

    You want to use scala.util.Using, like for instance:

    Using(new FileWriter(file)) { fileWriter =>
      // Use the fileWriter
      // No need to explicitly close it
      ???
    } match {
      case Failure(_) => ???
      case Success(_) => ???
    }
    

    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.

    See documentation (Scala 3 but applies to 2.13 as well).

    If using Scala < 2.13, you can still use Using thanks to the (badly-named) https://github.com/scala/scala-collection-compat which backports Using.