Finally, the equivalent in Scala Try

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

I am trying to idiomatically verify that the lock is released when exiting doWork. However, as part of this method, I can throw an exception, so I cannot just release the lock at the end doWork.

It seems like a bit of code smell to be releaseLock()repeated twice. I could shorten this using the traditional try / catch / finally Java style:

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

But I prefer to use Scala Try, if possible.

Is there a way to execute the β€œfinal” logic within the framework Try?

+4
source share
1 answer

Just take it Trytemporarily:

def doWork = {
  getLock()
  val t = Try(useResource)
  releaseLock()
  t.get
}
+5
source

Source: https://habr.com/ru/post/1615660/


All Articles