Created
November 19, 2014 14:30
-
-
Save coder36/bf4ca14cf9f1f411cdbe to your computer and use it in GitHub Desktop.
Scala 'using' implementation
This file contains hidden or 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 UsingDemo { | |
def main( args : Array[String] ) { | |
using( new A() ) { a => | |
a.print("Hello World " ) | |
} | |
} | |
def using[A, B <: {def close(): Unit}] ( closeable:B ) ( f: B => A ) : A = { | |
try { | |
f(closeable) | |
} | |
finally { | |
closeable.close() | |
} | |
} | |
class A { | |
def print(s:String) = { | |
println( s ) | |
} | |
def close() = { | |
println( "closing" ) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment