I'm quite new to Scala and was surprised that there doesn't seem to be anything like Java's try-with-resources block. So of course I wrote my own little construct. Is there anything I could improve?import scala.util.control.NonFatalimport scala.util.Tryimport scala.util.Failureimport scala.util.Successobject TryWith {  def apply [Closable <: { def close() }, Result]      (resGen: => T) (r: (Closable) => Result): Try[Result] = {    Try(resGen) match {      case Success(closable) => {        try Success(r(closable)) catch {          case NonFatal(e) => Failure(e)        } finally {          try {            closable.close()          } catch {            case e: Exception => {              System.err.println(Failed to close Resource:)              e.printStackTrace()            }          }        }      }      case Failure(e) => Failure(e)    }  }}Examples:val res = TryWith(Source.fromFile(foo.bar)) {  _.mkString}res match {  case Success(str) => println(str)  case Failure(e) => e.printStackTrace()}--TryWith(new BufferedReader(new FileReader(foo.bar)))((reader)=> {  var line = reader.readLine()  while(line != null) {    println(line)    line = reader.readLine()  } })Right now there is no way to react to or even detect a failed attempt to close the resource. I can see four ways to make that possbile but I'm not that happy with any of them:Instead of catching the Exception, let it through. It can now be dealt with but kind of defeats the purpose of the whole TryWith block.Return a Failure[Result] if closing fails. I don't like this because the action was actually a success and there is a valid result. By returning a Failure that result is lost.Return a pair of Trys, i.e. (Try[Result], Try[Unit]). The first one is the result of the operation, the second one is the result of the closing.Pass a (Closable) => Unit error handler as argument. This would also allow trying to close the resource again (which most likely won't change anything though).Is handling a failed close even important enough to think about? I know it can happen but usually there is no way to recover from it.
Scala TryWith that closes resources automatically
scala