With continued progress on JDK 8 efforts, I thought we'd explore some of its features together over the next few blog posts. Features added to Java in JDK 8 include:
- Nashorn JavaScript engine
- Date & Time API
- Bulk data operations for collections
- Lambda expressions and virtual extension methods
The first feature I'd like to touch on in this series is lambda expressions, also known as closures. A lambda expression is a function that may have parameters, an expression or block of code, optionally returning a value.
One very convenient use of lambda expressions is to simplify event handling. Typically, event handling is implemented with the help of an anonymous inner class, as shown in the following code snippet.
The anonymous inner class shown above is of type EventHandler, which has one abstract method, named handle. Any interface that has exactly one abstract method is known as a functional interface, and may be replaced by a lambda expression. The following code snippet contains a lambda expression that replaces the anonymous inner class in the previous code snippet. Note that the type of the lambda is inferred by the compiler as EventHandler<ActionEvent> because the onAction() method takes an object of type EventHandler<ActionEvent>. Furthermore, EventHandler has a single method handle(). Therefore, the lambda expression must be an implementation of the handle() method.
The parameter in this lambda expression must be an ActionEvent, because that is the type specified by the handle() method of the EventHandler interface. We can therefore simplify this lambda expression further because the parameter type is inferred, as shown in the following snippet.
When a lambda expression has a single parameter and its type is inferred, the parentheses are not required, as shown in the following snippet.
Because the block of code in our lambda expression contains only one statement, we can simplify it even further as shown in the following snippet.
The listing below contains a modified version of the MetronomeTransition example from the Pro JavaFX 2 book. Specifically, the event handlers in the listing below use lambda expressions rather than anonyomous inner classes.
Here's a screenshot of the MetronomeTransition example in action:
To compile and run this example, you'll need to download an early access release of JDK 8. You also may want to download NetBeans with preliminary JDK 8 support which is aware of lambda expression syntax.
Future articles in this JDK 8 series will dig deeper into lambdas and related topics such as bulk data operations for collections referenced at the beginning of this post. Have fun experimenting with lambda expressions and JDK 8 in general!
Regards,
James Weaver
james dot weaver at oracle dot com
Comments