Session 9 |
Simplifying event handling using lambda expressions
Lambda expressions can be used to greatly simplify coding for the event handling. The lambda expression can be used for Java 8 or later version. Lambda expressions can be viewed as an anonymous class with a concise syntax. For example, the following code on the left can be greatly simplified using a lambda expression on the right.
The basic syntax for a lambda expression is either
(type1 param1, type2 param2, ...) -> expression
or
(type1 param1, type2 param2, ...) -> { statements; }
The data type for a parameter may be explicitly declared or implicitly inferred by the compiler. The parentheses can be omitted if there is only one parameter without an explicit data type. In the previous example, the lambda expression is as follows
event -> { circle.setRadius(circle.getRadius() + 2); }
The compiler treats a lambda expression as if it is an object created from an anonymous inner class. In this case, the compiler understands that the object must be an instance of EventHandler<ActionEvent>
. Since the EventHandler
interface defines the handle
method with a parameter of the ActionEvent
type, the compiler automatically recognizes that event
is a parameter of the ActionEvent
type, and the statements are for the body of the handle
method. The EventHandler
interface contains only one method. The statements in the lambda expression are all for that method. If it contains multiple methods, the compiler will not be able to compile the lambda expression. So, to make a lambda expression understandable to the compiler, the interface must contain exactly one abstract method. Such an interface is known as a functional interface or a single abstract method (SAM) interface.
Session 9 |