Java Reference
In-Depth Information
Listing 5-20. Accessing Local and Instance Variables Inside Lambda Expressions
// VariableCapture.java
package com.jdojo.lambda;
public class VariableCapture {
private int counter = 0;
public static void main(String[] args) {
VariableCapture vc1 = new VariableCapture();
VariableCapture vc2 = new VariableCapture();
// Create lambdas
Printer p1 = vc1.createLambda(1);
Printer p2 = vc2.createLambda(100);
// Execute the lambda bodies
p1.print("Lambda #1");
p2.print("Lambda #2");
p1.print("Lambda #1");
p2.print("Lambda #2");
p1.print("Lambda #1");
p2.print("Lambda #2");
}
public Printer createLambda(int incrementBy) {
Printer printer = msg -> {
// Accesses instance and local variables
counter += incrementBy;
System.out.println(msg + ": counter = " + counter);
};
return printer;
}
}
Lambda #1: counter = 1
Lambda #2: counter = 100
Lambda #1: counter = 2
Lambda #2: counter = 200
Lambda #1: counter = 3
Lambda #2: counter = 300
The createLambda() method uses a lambda expressions to create an instance of the Printer functional interface.
The lambda expression uses the method's parameter incrementBy . Inside the body, it increments the instance
variable counter and prints its value. The main() method creates two instances of the VariableCapture class and
calls the createLambda() method on those instances by passing 1 and 100 as incrementBy values. The print()
method of the Printer objects are called three times for both instances. The output shows that the lambda expression
captures the incrementBy value and it increments the counter instance variable every time it is called.
 
Search WWH ::




Custom Search