Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finally equivalent in Scala Try [duplicate]

Tags:

scala

def doWork() = {
  getLock()
  Try(useResource) match {
    case Success(result) => releaseLock(); result
    case Failure(e: Exception) => releaseLock(); throw e
  }
}

I'm trying to idiomatically make sure a lock is released when I exit doWork. However as part of that method I may throw an exception, so I can't just release the lock at the end of doWork.

It looks like a bit of code smell to have releaseLock() repeated twice. I could cut that down by using the traditional Java-style try/catch/finally:

def doWork() = {
  getLock()
  try {
    useResource
  } catch {
    case e: Exception => throw e
  } finally {
    releaseLock()
  }
}

But I prefer to use Scala's Try if possible.

Is there a way to perform "finally" logic from within the framework of Try?

like image 873
Cory Klein Avatar asked Nov 12 '15 22:11

Cory Klein


People also ask

What is finally in Scala?

Scala finally block is used to execute important code such as closing connection, stream or releasing resources( it can be file, network connection, database connection etc). It will be always executed not matter if an exception is thrown or not.

Can try Have Multiple finally?

You can only have one finally clause per try/catch/finally statement, but you can have multiple such statements, either in the same method or in multiple methods. Basically, a try/catch/finally statement is: try.

What is try in Scala?

The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala. util. Either type. Instances of Try[T] , are either an instance of scala.


1 Answers

Just squirrel the Try away temporarily:

def doWork = {
  getLock()
  val t = Try(useResource)
  releaseLock()
  t.get
}
like image 197
Sean Avatar answered Sep 22 '22 18:09

Sean