Java Reference
In-Depth Information
A
:
Yes. However, when the type of the parameter is inferred, the parameter to the
lambda expression is
not
specified using the normal array syntax. Rather, the para-
meter is specified as a simple name, such as
n
, not as
n[ ]
. Remember, the type of a
lambda expression parameter will be inferred from the target context. Thus, if the tar-
get context requires an array, then the parameter's type will automatically be inferred
as an array. To better understand this, let's work through a short example.
Here is a generic functional interface called
MyTransform
, which can be used to apply
some transform to the elements of an array:
Notice that the parameter to the
transform( )
method is an array of type
T
. Now, consider
the following lambda expression that uses
MyTransform
to convert the elements of an
array of
Double
values into their square roots:
Here, the type of
a
in
transform( )
is
Double[ ]
, because
Double
is specified as the type
parameter for
MyTransform
when
sqrts
is declared. Therefore, the type of
v
in the
lambda expression is inferred as
Double[ ]
. It is not necessary (or legal) to specify it as
v[
]
.
One last point: It is legal to declare the lambda parameter as
Double[ ] v
, because doing
so explicitly declares the type of the parameter. However, doing so gains nothing in this
case.
Method References
There is an important feature related to lambda expressions called the
method reference
.
A method reference provides a way to refer to a method without executing it. It relates to
lambda expressions because it, too, requires a target type context that consists of a compat-
ible functional interface. When evaluated, a method reference also creates an instance of