Last active
July 23, 2018 15:02
-
-
Save dpsoft/9013481 to your computer and use it in GitHub Desktop.
Execute Around Method Pattern: Java 8 vs Scala
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
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(); | |
}); | |
} | |
} |
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
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't think the Java 8 solution works. Or does it?