Java Reference
In-Depth Information
The asList() method takes a varargs argument of type T and returns a List<T> . You can use Arrays::asList
as the method reference for this method. The syntax for the method reference allows you to specify the actual type
parameter for the method just after the two consecutive colons. For example, if you are passing String objects to the
asList() method, its method reference can be written as Arrays::<String>asList .
the syntax for a method reference also supports specifying the actual type parameters for generic types.
the actual type parameters are specified just before the two consecutive colons. For example, the constructor reference
ArrayList<Long>::new specifies Long as the actual type parameter for the generic ArrayList<T> class.
Tip
The following snippet of code contains an example of specifying the actual type parameter for the generic
method Arrays.asList() . In the code, Arrays::asList will work the same as the compiler will infer String as the
type parameter for the asList() method by examining the target type.
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
...
Function<String[],List<String>>asList = Arrays::<String>asList;
String[] namesArray = {"Jim", "Ken", "Li"};
List<String> namesList = asList.apply(namesArray);
for(String name : namesList) {
System.out.println(name);
}
Jim
Ken
Li
Lexical Scoping
A scope is the part of a Java program within which a name can be referred to without using a qualifier. Classes and
methods define their own scope. Scopes may be nested. For example, a method scope does not exist independently as
a method is always part of another construct, for example a class; an inner class appears inside the scope of another
class; a local or anonymous class appears inside the scope of a method.
Even though a lambda expression looks like a method declaration, it does not define a scope of its own. It
exists in its enclosing scope. This is known as lexical scoping for lambda expressions. For example, when a lambda
expression is used inside a method, the lambda expression exists in the scope of the method.
The meanings of the keywords this and super are the same inside the lambda expression and its enclosing
method. Note that this is different from the meanings of these keywords inside a local and anonymous inner class in
which the keyword this refers to the current instance of the local and anonymous inner class, not its enclosing class.
Listing 5-18 contains code for a functional interface named Printer that you will use to print messages in
examples in this section.
 
 
Search WWH ::




Custom Search