Java Reference
In-Depth Information
lambda expression also makes the Runnable implementation easier to read and main-
tain.
How It Works
Since java.util.Runnable is a functional interface, the boilerplate of imple-
menting the run() method can be abstracted away using a lambda expression. The
general format for implementing a Runnable with a lambda expression is as follows:
Runnable assignment = () -> {expression or statements};
A Runnable can be implemented by using a zero-argument lambda expression
containing an expression or a series of statements within the lambda body. The key is
that the implementation takes no arguments and returns nothing.
6-6. Replacing Anonymous Inner Classes
Problem
Portions of your code contain anonymous inner classes, which are sometimes difficult
to follow. You would like to replace anonymous inner classes with code that is easier to
read and maintain.
Solution
Replace the anonymous inner classes with lambda expressions. By doing so, develop-
ment time will be much faster as there will be fewer lines of boilerplate code required.
A typical JavaFX application utilizes anonymous inner classes to add functionality to
application constructs. For instance, anonymous classes are a great way to add an ac-
tion to a button. The problem is that inner classes can be difficult to follow, and they
contain lots of boilerplate code.
The following lines of code demonstrate a typical anonymous inner class imple-
mentation for a button action implementation. Let's look at these lines of code before
taking a look at how you can achieve the same solution using a lambda expression.
Search WWH ::




Custom Search