vatsal mevada
vatsal mevada

Reputation: 5636

Cleaner approach for quetly closing multiple resources in Scala

I am having multiple resources and I want to quietly close them in the finally block.

Following is the current approach that I am using. Is there any better (preferably a more concise and readable) approach to achieve the same?

I am also looking for some cleaner way to eliminate the use of var for storing resources.

    var connection1 = getConnection()
    var connection2 = getConnection()
    try {
      // do stuff
    } finally {
      try {
        if (connection1 != null) connection1.close()
      } catch {
        case NonFatal(_) => // log exception
      }
      try {
        if (connection2 != null) connection2.close()
      } catch {
        case NonFatal(_) => // log exception
      }
    }

Edit: I know that I can keep a collection of resources and loop over them to close them making the code concise. However, I am curious whether there is some better scala construct to make it more concise.

Upvotes: 1

Views: 589

Answers (1)

pme
pme

Reputation: 14803

With Scala 2.13 it is quite nice:

import scala.util.Using
import java.io.{FileReader, FileWriter}
Using.resources(
  new FileReader("input.txt"), 
  new FileWriter("output.txt")) { (reader, writer) => 
    ???
}

This will do all the work for you.

I found this here: my-favorite-new-features-of-scala-2-13

There is also a link if you cannot use 2.13: scala-try-with-resources

Upvotes: 6

Related Questions