Skip to content

Instantly share code, notes, and snippets.

@dmyersturnbull
Created August 4, 2016 20:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmyersturnbull/37f85b7703ea07f5cf88d614a32c98b8 to your computer and use it in GitHub Desktop.
Save dmyersturnbull/37f85b7703ea07f5cf88d614a32c98b8 to your computer and use it in GitHub Desktop.
Scala try-with-resources
import java.io.Closeable
import scala.util.control.NonFatal
import scala.util.{Failure, Try}
/**
* Taken from user Morgen on StackOverflow with no substantive modifications:
* https://codereview.stackexchange.com/questions/79267/scala-trywith-that-closes-resources-automatically
* Which is licensed under cc-wiki with attribution required.
*/
object TryWith {
def apply[C <: Closeable, R](resource: => C)(f: C => R): Try[R] =
Try(resource).flatMap(resourceInstance => {
try {
val returnValue = f(resourceInstance)
Try(resourceInstance.close()).map(_ => returnValue)
} catch {
case NonFatal(exceptionInFunction) =>
try {
resourceInstance.close()
Failure(exceptionInFunction)
} catch {
case NonFatal(exceptionInClose) =>
exceptionInFunction.addSuppressed(exceptionInClose)
Failure(exceptionInFunction)
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment