Java Reference
In-Depth Information
For each file in the list, the block of code in the lambda expression is evaluated. If
the method returns true (which happens if the filename ends in .java ) then the file
is included in the output—which ends up in the array filelist .
This pattern, where a block of code is used to test if an element of a container
matches a condition, and to only return the elements that pass the condition, is
called a ilter idiom —and is one of the standard techniques of functional program‐
ming, which we will discuss in more depth presently.
Lambda Expression Conversion
When javac encounters a lambda expression, it interprets it as the body of a
method with a specific signature—but which method?
To resolve this question, javac looks at the surrounding code. To be legal Java code,
the lambda expression must satisfy the following:
• The lambda must appear where an instance of an interface type is expected.
• The expected interface type should have exactly one mandatory method.
• The expected interface method should have a signature that exactly matches
that of the lambda expression.
If this is the case, then an instance is created of a type that implements the expected
interface, and uses the lambda body as the implementation for the mandatory
method.
This slightly complex explanation comes from the decision to keep Java's type sys‐
tem as purely nominative (based on names). The lambda expression is said to be
converted to an instance of the correct interface type.
Some developers also like to use the term single abstract method (or SAM) type to
refer to the interface type that the lambda is converted into. This draws attention to
the fact that to be usable by the lambda expression mechanism, an interface must
have only a single nondefault method.
Despite the parallels between lambda expressions and anony‐
mous classes, lambdas are not simply syntactic sugar over
anonymous classes. In fact, lambdas are implemented using
method handles (which we will meet in Chapter 11 ) and a
new, special JVM bytecode called invokedynamic .
From this discussion, we can see that although Java 8 has added lambda expres‐
sions, they have been specifically designed to fit into Java's existing type system—
which has a very strong emphasis on nominal typing.
Search WWH ::




Custom Search