Java Reference
In-Depth Information
Anonymous inner classes were designed to make it easier for Java programmers to pass
around code as data. Unfortunately, they don't make it easy enough. There are still four lines
of boilerplate code required in order to call the single line of important logic. Look how
much gray we get if we color out the boilerplate:
button . addActionListener ( new
new ActionListener () {
public
public void
void actionPerformed ( ActionEvent event ) {
System . out . println ( "button clicked" );
}
});
Boilerplate isn't the only issue, though: this code is fairly hard to read because it obscures the
programmer's intent. We don't want to pass in an object; what we really want to do is pass in
some behavior. In Java 8, we would write this code example as a lambda expression, as
shown in Example 2-2 .
Example 2-2. Using a lambda expression to associate behavior with a button click
button . addActionListener ( event -> System . out . println ( "button clicked" ));
Instead of passing in an object that implements an interface, we're passing in a block of
code—a function without a name. event is the name of a parameter, the same parameter as
in the anonymous inner class example. -> separates the parameter from the body of the
lambda expression, which is just some code that is run when a user clicks our button.
Another difference between this example and the anonymous inner class is how we declare
the variable event . Previously, we needed to explicitly provide its type— ActionEvent
event . In this example, we haven't provided the type at all, yet this example still compiles.
What is happening under the hood is that javac is inferring the type of the variable event
from its context—here, from the signature of addActionListener . What this means is that
you don't need to explicitly write out the type when it's obvious. We'll cover this inference
in more detail soon, but first let's take a look at the different ways we can write lambda ex-
pressions.
Search WWH ::




Custom Search