Last active
January 1, 2016 20:29
-
-
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.
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
object ImAClosable { | |
def work() = { | |
println("working...") | |
} | |
def close() { | |
prinlnt("closing...") | |
} | |
} | |
object ImNotClosable { | |
def work() = { | |
println("just wait...") | |
} | |
} |
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
object Main1 { | |
def main(args: Array[String]) { | |
ResourceHandler.managed(ImAClosable) { // prints working... and then closing... | |
work() | |
} | |
} | |
} |
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
object Main2 { | |
def main(args: Array[String]) { | |
ResourceHandler.managed(ImNotClosable) { // <- doesn't compile! | |
work() | |
} | |
} | |
} |
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
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