Home >Java >javaTutorial >Why Do Lambda Expressions Require Final or Effectively Final Variables?
The error message "Variable used in lambda expression should be final or effectively final" arises when attempting to use a non-final variable within a lambda expression. This requirement ensures the captured variable's immutability.
In the provided code snippet:
private TimeZone extractCalendarTimeZoneComponent(Calendar cal, TimeZone calTz) { ... cal.getComponents().getComponents("VTIMEZONE").forEach(component -> { ... if (calTz == null) { calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue()); } }); ... }
The variable calTz is used within the lambda expression and doesn't have a guaranteed final status. This violates the rule that lambda expressions can only capture variables that are final or effectively final.
Why is this rule in place? The Java Language Specification (JLS) explains in §15.27.2 that it prevents access to dynamically-changing local variables, mitigating concurrency issues. By ensuring captured variables are immutable, the language lowers the risk of bugs.
This requirement also applies to anonymous inner classes. Variables used within such classes must also be final or effectively final to ensure thread safety.
The above is the detailed content of Why Do Lambda Expressions Require Final or Effectively Final Variables?. For more information, please follow other related articles on the PHP Chinese website!