Skip to content

Instantly share code, notes, and snippets.

@marceloemanoel
Last active January 1, 2016 20:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marceloemanoel/8197340 to your computer and use it in GitHub Desktop.
Save marceloemanoel/8197340 to your computer and use it in GitHub Desktop.
Use Structural Typing to safely close any resource while using it in a transparent manner.
object ImAClosable {
def work() = {
println("working...")
}
def close() {
prinlnt("closing...")
}
}
object ImNotClosable {
def work() = {
println("just wait...")
}
}
object Main1 {
def main(args: Array[String]) {
ResourceHandler.managed(ImAClosable) { // prints working... and then closing...
work()
}
}
}
object Main2 {
def main(args: Array[String]) {
ResourceHandler.managed(ImNotClosable) { // <- doesn't compile!
work()
}
}
}
object ResourceHandler {
def managed[X <: {def close(): Unit}, Y](resource: X)(f: X => Y) = {
Option(resource) match {
case None => throw new NullPointerException("Can't close a null resource")
case Some(value) =>
implicit val implicitResource = value
try {
f(implicitResource)
}
finally {
implicitResource.close()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment