Skip to content

Instantly share code, notes, and snippets.

@dpsoft
Last active July 23, 2018 15:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpsoft/9013481 to your computer and use it in GitHub Desktop.
Save dpsoft/9013481 to your computer and use it in GitHub Desktop.
Execute Around Method Pattern: Java 8 vs Scala
import java.util.function.Consumer;
import static java.lang.System.out;
class JavaResource {
private JavaResource() {out.println("created...");}
public void operation1() {out.println("operation 1");}
public void operation2() {out.println("operation 2");}
private void close() { out.println("cleanup");}
public static void use(Consumer<JavaResource> block) {
JavaResource resource = new JavaResource();
try {
block.accept(resource);
} finally {
resource.close();
}
}
}
public class Main {
public static void main(String... args) {
JavaResource.use(resource -> {
resource.operation1();
resource.operation2();
});
}
}
class ScalaResource private {
println("created...")
def operation1() = println("operation 1")
def operation2() = println("operation 2")
private def close() = println("cleaning up")
}
object ScalaResource {
def use(closure : ScalaResource => Unit) = {
val resource = new ScalaResource
try {
closure(resource)
} finally {
resource.close()
}
}
}
object MainEAM extends App {
ScalaResource.use { resource =>
resource.operation1()
resource.operation2()
}
}
@devacto
Copy link

devacto commented Jul 3, 2016

I don't think the Java 8 solution works. Or does it?

@vzedano
Copy link

vzedano commented Sep 27, 2016

It does in Java 8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment