Skip to content

Instantly share code, notes, and snippets.

@jehugaleahsa
Created October 5, 2016 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jehugaleahsa/396f5eddc73b23e3c34720a06b8f02bc to your computer and use it in GitHub Desktop.
Save jehugaleahsa/396f5eddc73b23e3c34720a06b8f02bc to your computer and use it in GitHub Desktop.
Scala ARM
import scala.language.reflectiveCalls
def using[TResource <: { def close(): Unit }, TResult](resource: => TResource)(action: TResource => TResult): TResult = {
val instance = resource
try {
action(instance)
} finally {
instance.close()
}
}
def manage[TResource <: { def close(): Unit }](resource: => TResource): Traversable[TResource] = new Traversable[TResource] {
override def foreach[TResult](action: TResource => TResult): Unit = {
val instance = resource
try {
action(instance)
} finally {
instance.close()
}
}
}
class Resource {
scala.Console.out.println("Opening...")
def close() {
scala.Console.out.println("Closing...")
}
}
using (new Resource) { r =>
}
for (r <- manage(new Resource)) {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment