Sub topic 6
Using Local Variables Inside Lambdas
A lambda often needs a value that comes from outside its own body. For example, a greeting lambda needs to know which greeting to use. Java lets a lambda read variables from the method around it, but it adds one important rule. This chapter explains that rule, why it exists, and what to do when it gets in your way.
What "capturing" means
A local variable is a variable declared inside a method, such as String greeting = "Hello";. When a lambda uses a local variable from the surrounding method, we say the lambda captures that variable.
Here is a lambda that captures greeting:
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 gets name as its parameter. It gets greeting from the method around it. Both work inside the body.
The rule: final or effectively final
A lambda may only capture a local variable if that variable is final or effectively final.
- A final variable is marked with the
finalkeyword, so it can never be given a new value. - An effectively final variable has no
finalkeyword, but the code never gives it a new value after it is first set. The compiler checks this for you.
In the example above, greeting is set once and never changed, so it is effectively final. If you remove the // from the line greeting = "Hi";, the program no longer compiles. The compiler shows this message:
error: local variables referenced from a lambda expression must be final or effectively finalNote where the error is reported. It points at the lambda, not at the line that changes greeting. That can be confusing. The lambda is the code that broke the rule, even though the change happens somewhere else.
The rule covers changes made anywhere in the method: before the lambda, after it, or inside it.
import java.util.function.Supplier;
public class NotEffectivelyFinal {
public static void main(String[] args) {
int total = 10;
total = total + 5; // total has now been reassigned
// This would not compile, because total is not effectively final:
// Supplier<Integer> s = () -> total;
int finalTotal = total; // a new variable, set once
Supplier<Integer> s = () -> finalTotal; // OK
System.out.println(s.get()); // 15
}
}The fix in the last lines is the most common workaround. You copy the value into a new variable that you never change, and the lambda captures the copy.
Why Java has this rule
A lambda is a piece of behavior that may run later. You might store it in a list, hand it to another method, or run it on another thread. By the time it runs, the method that created it may already have finished, and that method's local variables are gone.
To handle this, Java gives the lambda its own copy of each captured value when the lambda is created. If the original variable could change later, the copy and the original would disagree, and nobody could tell which value the lambda would see. The effectively-final rule removes that problem. When a variable can never change, the copy and the original always hold the same value.
Changing an object is different from reassigning a variable
The rule is about the variable, not about the object it points to. A variable that holds a list is effectively final as long as you never point it at a different list. You can still add items to the list.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class MutateVsReassign {
public static void main(String[] args) {
List<String> seen = new ArrayList<>();
Consumer<String> recorder = s -> seen.add(s); // OK: changes the list, not the variable
recorder.accept("a");
recorder.accept("b");
System.out.println(seen); // [a, b]
// This line would break the lambda, because it reassigns the variable:
// seen = new ArrayList<>();
}
}| Action inside or outside the lambda | Allowed? | Why |
|---|---|---|
| `seen.add("x")` | Yes | The variable still points to the same list |
| `seen.clear()` | Yes | Same list, different contents |
| `seen = new ArrayList<>()` | No | The variable gets a new value |
| `count++` on a local `int` | No | `++` gives the variable a new value |
Fields are not covered by the rule
A field is a variable that belongs to an object or class, declared outside any method. Fields do not live in the method's local storage. The lambda reaches them through the object, so it reads the current value every time. Because of this, a lambda may read and change fields.
import java.util.function.Consumer;
public class CountWithField {
private int count = 0;
void countLongWords(String[] words) {
Consumer<String> counter = w -> {
if (w.length() > 3) {
count++; // allowed: count is a field, not a local variable
}
};
for (String w : words) {
counter.accept(w);
}
}
public static void main(String[] args) {
CountWithField c = new CountWithField();
c.countLongWords(new String[] {"hi", "hello", "lambda"});
System.out.println(c.count); // 2
}
}If count were a local variable inside countLongWords, the line count++ would not compile. The this keyword, and how lambdas see the surrounding object, is covered in a later chapter.
Counting with a local variable
Sometimes you do want a counter that is local to one method. You cannot write count++ on a local int, but you can use an object whose contents change. AtomicInteger is a class that holds one int and lets you change it safely, even across threads.
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
public class LocalCounter {
public static void main(String[] args) {
AtomicInteger count = new AtomicInteger(0); // the variable is never reassigned
Consumer<String> counter = w -> {
if (w.length() > 3) {
count.incrementAndGet(); // changes the object, not the variable
}
};
for (String w : new String[] {"hi", "hello", "lambda"}) {
counter.accept(w);
}
System.out.println(count.get()); // 2
}
}This works, but ask yourself first whether you need a lambda here at all. A plain for loop with an int counter is often clearer.
Loops: a common trap
The variable in a classic for loop, such as i in for (int i = 0; i < 3; i++), changes on every pass because of i++. So a lambda cannot capture i. The fix is to copy i into a new variable inside the loop body. Each pass creates a fresh copy that is never changed.
The variable in an enhanced for loop (for (String word : words)) is different. Java creates a new variable on each pass and never reassigns it, so it is effectively final.
import java.util.ArrayList;
import java.util.List;
public class LoopCapture {
public static void main(String[] args) {
List<Runnable> tasks = new ArrayList<>();
for (int i = 0; i < 3; i++) {
// tasks.add(() -> System.out.println("task " + i)); // would not compile
int copy = i; // new variable each pass, never reassigned
tasks.add(() -> System.out.println("task " + copy));
}
for (String word : new String[] {"x", "y"}) {
tasks.add(() -> System.out.println("word " + word)); // allowed
}
for (Runnable task : tasks) {
task.run();
}
// task 0
// task 1
// task 2
// word x
// word y
}
}Each lambda remembers its own value. The tasks run after both loops have finished, and each one still prints the value it captured.
Names inside a lambda
A lambda's body is part of the method around it. It does not get its own separate set of names. Because of that, two more rules apply:
- A lambda parameter cannot reuse the name of a local variable that is already in scope. If
nameis already a local variable,Consumer<String> c = name -> ...fails with "variable name is already defined". - Variables you declare inside a block body belong only to the lambda. You can change them freely, because each call of the lambda gets new ones.
import java.util.function.Function;
public class InsideTheBody {
public static void main(String[] args) {
Function<Integer, Integer> sumUpTo = n -> {
int sum = 0; // declared inside the lambda
for (int i = 1; i <= n; i++) {
sum += i; // fine: sum is the lambda's own variable
}
return sum;
};
System.out.println(sumUpTo.apply(4)); // 10
}
}Exercise
Does this code compile? If not, why, and how would you fix it? int limit = 5; if (args.length > 0) { limit = 10; } Predicate<Integer> small = n -> n < limit;
Show answer
It does not compile. limit can be reassigned inside the if statement, so it is not effectively final. The compiler reports that local variables referenced from a lambda expression must be final or effectively final. One fix is to copy the value after the if statement: int finalLimit = limit; and then use n -> n < finalLimit. Another fix is to set the variable only once: int limit = args.length > 0 ? 10 : 5;
Exercise
A local variable List<String> names = new ArrayList<>(); is captured by the lambda s -> names.add(s). Is that allowed? Would names = new ArrayList<>(); later in the method be allowed?
Show answer
The lambda is allowed, because add changes the list's contents and does not give the variable names a new value. The later line names = new ArrayList<>(); reassigns the variable, so names stops being effectively final and the lambda no longer compiles.
Exercise
Why can a lambda run count++ when count is a field, but not when count is a local variable?
Show answer
A lambda gets a copy of each captured local variable's value when it is created, so Java requires that value to never change. A field is not copied. The lambda reaches it through the object every time it runs, so it always sees the current value, and changing it is allowed.