Created
February 17, 2016 16:47
-
-
Save stanislav-chetvertkov/9f6d44c25edeb7b4b46b to your computer and use it in GitHub Desktop.
Try with resources in scala
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 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