Java Reference
In-Depth Information
This lambda expression obtains a pseudo-random value from Math.random( ) , multiplies
it by 100, and returns the result. It, too, does not require a parameter.
When a lambda expression requires a parameter, it is specified in the parameter list on
the left side of the lambda operator. Here is a simple example:
This lambda expression returns the reciprocal of the value of parameter n . Thus, if n is 4.0,
the reciprocal is 0.25. Although it is possible to explicitly specify the type of a paramet-
er, such as n in this case, often you won't need to because, in many cases, its type can be
inferred. Like a named method, a lambda expression can specify as many parameters as
needed.
Any valid type can be used as the return type of a lambda expression. For example, this
lambda expression returns true if the value of parameter n is even and false otherwise.
Thus, the return type of this lambda expression is boolean .
One other point before moving on. When a lambda expression has only one parameter,
it is not necessary to surround the parameter name with parentheses when it is specified
on the left side of the lambda operator. For example, this is also a valid way to write the
lambda expression just shown:
For consistency, this topic will surround all lambda expression parameter lists with paren-
theses, even those containing only one parameter. Of course, you are free to adopt a differ-
ent style.
Functional Interfaces
As stated, a functional interface is an interface that specifies only one abstract method. Be-
fore continuing, recall from Chapter 8 that not all interface methods are abstract. Beginning
with JDK 8, it is possible for an interface to have one or more default methods. Default
methods are not abstract. Neither are static interface methods. Thus, an interface method
is abstract only if it is does not specify an implementation. This means that a functional
interface can include default and/or static methods, but in all cases it must have one and
only one abstract method. Because non-default, non- static interface methods are implicitly
abstract, there is no need to use the abstract modifier (although you can specify it, if you
like).
Search WWH ::




Custom Search