Java 7
Runnable r1 = new Runnable() { @Override public void run() { System.out.println("Hello World!"); } };
Java 8
Runnable r2 = () -> System.out.println("Hello World!");
// With parameters + multiple lines button.setOnAction(event -> { System.out.println("Thanks for clicking!"); return event.data; });
Verbose syntax
button.setOnAction(event -> System.out.println(event));
With method reference
button.setOnAction(System.out::println);
// Calculate Sum of the weights of red blocks List<Block> blocks = /* ... */; int sumOfWeights = 0; for (Block block : blocks) { if (block.getColor() == Color.RED) { sumOfWeights += block.getWeight(); } }
// Calculate Sum of the weights of red blocks List<Block> blocks = /* ... */; int sumOfWeights = blocks.stream() // Stream<Block> .filter(b -> b.getColor() == Color.RED) .mapToInt(b -> b.getWeight()) // IntStream .sum();
Declarative, type-safe URL Mapping
VERB PATH CONTROLLER_METHOD GET / controllers.Application.index() GET /foo controllers.Application.foo()
public static Result index() { return ok("Hello World!"); }
import play.libs.F.*; public static Integer calc() { return (5134 * 5789) / 349; } public static Promise<Result> basicPromise() { Promise<Integer> promise = Promise.promise(() -> calc()); return promise.map((Integer i) -> ok("Result is: " + i)); }
public static Promise<Result> getPage() { final Promise<WS.Response> promise = WS.url("http://google.com").get(); return promise.map(response -> ok(response.getBody())); }
public static Promise<Result> composition() { final Promise<WS.Response> googlePromise = WS.url("http://google.com").get(); final Promise<WS.Response> twitterPromise = WS.url("http://twitter.com").get(); return googlePromise.flatMap((google) -> twitterPromise.map((twitter) -> ok(google.getBody() + twitter.getBody()))); }
CoffeeScript (Client)
events = new EventSource("/events") events.onmessage = (event) -> alert(event.data)
Controller (Server)
public static Result events() { return ok(new EventSource() { public void onConnected() { send(Event.event("hello")); } }); }
CoffeeScript (Client)
ws = new WebSocket("ws://url/echo") ws.onmessage = (event) -> alert(event.data) ws.onopen = () -> ws.send("Echo")
Controller (Server)
public static WebSocket<String> echo() { return new WebSocket<String>() { public void onReady(final In<String> in, final Out<String> out) { in.onMessage(out::write); } }; }
A single unified programming model for
Akka decouples communication from failure handling: