Sub topic 6
Using Local Variables Inside Lambdas
A lambda often needs a value from the method around it, such as a greeting, a limit, or a prefix. Java lets a lambda use these values, but only under one simple rule. This chapter explains that rule and shows how to work with it.
What Capturing Means
A local variable is a variable declared inside a method. When a lambda uses a local variable from the method around it, we say the lambda captures that variable.
Here is an example:
import java.util.function.Consumer;
public class CaptureExample {
public static void main(String[] args) {
String greeting = "Hello"; // never reassigned, so effectively final
Consumer<String> greeter = name -> System.out.println(greeting + ", " + name);
greeter.accept("Ada"); // Hello, Ada
// Uncommenting the next line makes the lambda above fail to compile,
// because greeting would no longer be effectively final.
// greeting = "Hi";
}
}The lambda does not declare greeting. It borrows it from main.
The Effectively-Final Rule
A lambda may capture a local variable only if that variable is final or effectively final.
- A final variable is marked with the
finalkeyword, so it can never be changed. - An effectively final variable has no
finalkeyword, but your code never assigns it a new value after it is first set.
In the example, greeting gets a value once and never changes, so it is effectively final. If you remove the // in front of greeting = "Hi";, the compiler stops with an error like this:
error: local variables referenced from a lambda expression must be final or effectively finalThe error points at the lambda, even though the line that breaks the rule comes later.
Why the Rule Exists
A lambda can run later, after the method has finished. Java gives the lambda its own copy of the variable's value. If the original variable could change, the copy and the original would disagree. The rule makes sure they always hold the same value.
A Common Trap: Loop Counters
The counter in a classic for loop changes on every pass (i++), so a lambda cannot capture it. The fix is to copy the counter into a new variable inside the loop. A fresh number is created on each pass and never changes, so it is effectively final.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class LoopCapture {
public static void main(String[] args) {
List<Supplier<String>> tasks = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
int number = i; // new variable each time, never reassigned
tasks.add(() -> "Task " + number);
// tasks.add(() -> "Task " + i); // would not compile
}
for (Supplier<String> task : tasks) {
System.out.println(task.get());
}
// Task 1
// Task 2
// Task 3
}
}What the Rule Does and Does Not Cover
| Situation | Allowed? |
|---|---|
| Reading a local variable that is never reassigned | Yes |
| Reading a local variable that is reassigned anywhere | No |
| Assigning a new value to a local variable inside the lambda | No |
| Reading or changing a field of the class | Yes |
| Calling a method on a captured object, such as `list.add(x)` | Yes |
The rule covers the variable itself, not the object it points to. If you capture a list, you can still add items to that list. You just cannot make the variable point to a different list.
Exercise
Will this code compile? int count = 0; Runnable r = () -> System.out.println(count); count = 5; Explain why or why not.
Show answer
No. The line count = 5; reassigns count, so it is not effectively final, and the lambda is not allowed to capture it. Removing the reassignment, or copying the value into a new variable that never changes, fixes it.
Exercise
Inside a for (int i = 0; i < 5; i++) loop, you want to add () -> i * 10 to a list of suppliers. What change makes it compile?
Show answer
Copy the counter into a new variable inside the loop, such as int value = i;, and use () -> value * 10. The variable value is created fresh on each pass and never reassigned, so it is effectively final.