Java Reference
In-Depth Information
name will function all the same
. In an effort to avoid such pointless debate, I'll be referring
to them as “lambda expressions” throughout this topic. Regardless of what we call them, I've
already mentioned that lambda expressions are statically typed, so let's investigate the types
of lambda expressions themselves: these types are called
functional interfaces
.
Functional Interfaces
NOTE
A functional interface is an interface with a single abstract method that is used as the type
of a lambda expression.
In Java, all method parameters have types; if we were passing
3
as an argument to a method,
the parameter would be an
int
. So what's the type of a lambda expression?
There is a really old idiom of using an interface with a single method to represent a method
and reusing it. It's something we're all familiar with from programming in Swing, and it is
exactly what was going on in
Example 2-2
.
There's no need for new magic to be employed
here. The exact same idiom is used for lambda expressions, and we call this kind of interface
a
functional interface
.
Example 2-8
shows the functional interface from the previous ex-
ample.
Example 2-8. The ActionListener interface: from an ActionEvent to nothing
public
public interface
interface
ActionListener
ActionListener
extends
extends
EventListener
{
public
public
void
void
actionPerformed
(
ActionEvent event
);
}
ActionListener
has only one abstract method,
actionPerformed
, and we use it to
repres-
ent
an action that takes one argument and produces no result. Remember, because
ac-
tionPerformed
is defined in an interface, it doesn't actually need the
abstract
keyword in
order to be abstract. It also has a parent interface,
EventListener
, with no methods at all.
So it's a functional interface. It doesn't matter what the single method on the interface is
called—it'll get matched up to your lambda expression as long as it has a compatible method
signature. Functional interfaces also let us give a useful name to the type of the paramet-
er—something that can help us understand what it's used for and aid readability.