package com.weEat.util import scala.util.control.NonFatal import scala.util.{Failure, Try} /* Adopted with minor changes from: * https://codereview.stackexchange.com/questions/79267/scala-trywith-that-closes-resources-automatically * Written by Stack Overflow User Morgan */ object TryWith { def apply[C <: AutoCloseable, 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) } } }) }