Java Reference
In-Depth Information
Printer printer = msg1 -> System.out.println(
msg
+ " " + msg1);
msg
= "Hi"; // msg is changed
return printer;
}
The following snippet of code generates a compile-time error because the lambda expression accesses the
msg
variable that is declared lexically after its use. In Java, forward referencing of variable names in method's scope is not
allowed. Note that the
msg
variable is effectively final.
public Printer test() {
// A compile-time error. The msg variable is not declared yet.
Printer printer = msg1 -> System.out.println(
msg
+ " " + msg1);
String
msg
= "Hello"; // msg is effectively final
return printer;
}
Can you guess why the following snippet of code generates a compile-time error?
public Printer test() {
String
msg
= "Hello";
Printer printer = msg1 -> {
msg
= "Hi " + msg1; // A compile-time error. Attempting to modify msg.
System.out.println(
msg
);
};
return printer;
}
The lambda expression accesses the local variable
msg
. Any local variable accessed inside a lambda expression
must be effectively final. The lambda expression attempts to modify the
msg
variable inside its body that causes the
compile-time error.
■
a lambda expression can access instance and class variables of a class whether they are effectively final or not.
if instance and class variables are not final, they can be modified inside the body of the lambda expressions. a lambda
expression keeps a copy of the local variables used in its body. if the local variables are reference variables, a copy of the
references is kept, not a copy of the objects.
Tip
The program in Listing 5-20 demonstrates how to access the local and instance variables inside lambda
expressions.