TryWith.scala 912 B

123456789101112131415161718192021222324252627282930
  1. package com.weEat.util
  2. import scala.util.control.NonFatal
  3. import scala.util.{Failure, Try}
  4. /* Adopted with minor changes from:
  5. * https://codereview.stackexchange.com/questions/79267/scala-trywith-that-closes-resources-automatically
  6. * Written by Stack Overflow User Morgan
  7. */
  8. object TryWith {
  9. def apply[C <: AutoCloseable, R](resource: => C)(f: C => R): Try[R] =
  10. Try(resource).flatMap(resourceInstance => {
  11. try {
  12. val returnValue = f(resourceInstance)
  13. Try(resourceInstance.close()).map(_ => returnValue)
  14. }
  15. catch {
  16. case NonFatal(exceptionInFunction) =>
  17. try {
  18. resourceInstance.close()
  19. Failure(exceptionInFunction)
  20. }
  21. catch {
  22. case NonFatal(exceptionInClose) =>
  23. exceptionInFunction.addSuppressed(exceptionInClose)
  24. Failure(exceptionInFunction)
  25. }
  26. }
  27. })
  28. }