Lambda Capture Requires Effectively Final
Lambdas may only capture locals that are never reassigned: the compiler rejects captured variables that change, so mutable state flows through containers.
Code
import java.util.concurrent.atomic.AtomicInteger;
public class CaptureRules {
public static void main(String[] args) {
int base = 10;
// base = 11; 若放开这行,下面的 lambda 编译失败:
// 局部变量被 lambda 捕获后必须保持 effectively final(声明后不再重新赋值)
Runnable printer = () -> System.out.println("base = " + base);
// 想在 lambda 里累加:用可变容器承载状态,而不是裸局部变量
AtomicInteger counter = new AtomicInteger();
Runnable increment = () -> counter.incrementAndGet();
increment.run();
increment.run();
printer.run();
System.out.println("counter = " + counter.get());
// 增强 for 的循环变量每轮都是一次新绑定,捕获它完全合法
for (String token : new String[] {"alpha", "beta"}) {
Runnable shout = () -> System.out.println(token.toUpperCase());
shout.run();
}
}
}How it works
Lambda Capture Requires Effectively Final is built around the class CaptureRules and the function main.
for (String token : new String[] {"alpha", "beta"}) is the loop that carries the per-item work.
Caveats
- No external surface: all behavior comes from the standard library.
Putting it to use
The primary signature is public static void main(String[] args)
Running the file prints labeled results such as base =, counter = — each operation’s effect is visible in the output.
Core lines
Runnable increment = () -> counter.incrementAndGet();
AtomicInteger counter = new AtomicInteger();
increment.run();
Interactive Tools for This Topic
FAQ
- What does Lambda Capture Requires Effectively Final print when run?
- Running the file directly is enough — expect labeled output lines such as `base =`, `counter =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.