Skip to content

Instantly share code, notes, and snippets.

@stanislav-chetvertkov
Created February 17, 2016 16:47
Show Gist options
  • Save stanislav-chetvertkov/9f6d44c25edeb7b4b46b to your computer and use it in GitHub Desktop.
Save stanislav-chetvertkov/9f6d44c25edeb7b4b46b to your computer and use it in GitHub Desktop.
Try with resources in scala
import scala.util.{Failure, Success, Try}
class Loan[A <: AutoCloseable](resource: A) {
def to[B](block: A => B): B = {
Try(block(resource)) match {
case Success(result) =>
resource.close()
result
case Failure(e) =>
resource.close()
throw e
}
}
}
object Loan {
def loan[A <: AutoCloseable](resource: A): Loan[A] = new Loan(resource)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment