Monday, 9 April 2018

Scala Try With Resource

Java 7 introduced try-with-resources, which is a handy feature. It automatically closes resources once done, such as InputStreams and Database connections. This seems to be missing from Scala. However this feature can be easily added to Scala through function currying.

Below is a definition of a tryWith function

def tryWith[R, T <: AutoCloseable](resource: T)(doWork: T => R): R = {
  try {
    doWork(resource)
  }
  finally {
    try {
      if (resource != null) {
        resource.close()
      }
    }
    catch {
      case e: Exception => throw e
    }
  }
}




There are 2 functions. The first function takes an AutoCloseable resource. The second function uses the resource. The try finally block ensures the resource is closed once the second function returns.

Below is how the function can be used:

val request = new HttpGet("http://www.google.com")

val statusCode = tryWith(client.execute(request)){response =>
  response.getStatusLine.getStatusCode
}

client.execute() returns an AutoCloseable Response, which will be automatically closed. After return the StatusCode.


8 comments:

  1. Replies
    1. Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important. Project Center in Chennai It’s what organizations do with the data that matters. Big data can be analyzed for insights that lead to better decisions and strategic business moves.

      Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Corporate TRaining Spring Framework the authors explore the idea of using Java in Big Data platforms.
      Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai


      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    thanks for your information really good and very nice web design company in velachery

    ReplyDelete
  3. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info.

    Bloglovin Mystrikingly Justpaste Mystrikingly

    ReplyDelete