Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.