Created
August 4, 2016 20:47
-
-
Save dmyersturnbull/37f85b7703ea07f5cf88d614a32c98b8 to your computer and use it in GitHub Desktop.
Scala try-with-resources
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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