Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable used in lambda expression should be final or effectively final

Tags:

java

lambda

Variable used in lambda expression should be final or effectively final

When I try to use calTz it is showing this error.

private TimeZone extractCalendarTimeZoneComponent(Calendar cal, TimeZone calTz) {     try {         cal.getComponents().getComponents("VTIMEZONE").forEach(component -> {             VTimeZone v = (VTimeZone) component;             v.getTimeZoneId();             if (calTz == null) {                 calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue());             }         });     } catch (Exception e) {         log.warn("Unable to determine ical timezone", e);     }     return null; } 
like image 356
user3610470 Avatar asked Jan 18 '16 22:01

user3610470


People also ask

Why the variables used in lambda body should be final or effectively final?

Forcing the variable to be final avoids giving the impression that incrementing start inside the lambda could actually modify the start method parameter.

Can we use Non final variable in lambda?

A non-final local variable or method parameter whose value is never changed after initialization is known as effectively final. It's very useful in the context of the lambda expression. If you remember, prior to Java 8, we cannot use a non-final local variable in an anonymous class.

What is final or effectively final?

In simple terms, objects or primitive values are effectively final if we do not change their values after initialization. In the case of objects, if we do not change the reference of an object, then it is effectively final — even if a change occurs in the state of the referenced object.

Should method variables be final?

Like methods, local variables and parameters need not to be declared final. As others said before, this clutters the code becoming less readable with very little efford for compiler performace optimisation, this is no real reason for most code fragments.


1 Answers

Although other answers prove the requirement, they don't explain why the requirement exists.

The JLS mentions why in §15.27.2:

The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems.

To lower risk of bugs, they decided to ensure captured variables are never mutated.

like image 72
Vince Avatar answered Sep 18 '22 20:09

Vince