javalambda

Variable used in lambda expression should be final or effectively final


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;
}

Solution

  • A final variable means that it can be instantiated only one time. in Java you can't reassign non-final local variables in lambda as well as in anonymous inner classes.

    You can refactor your code with the old for-each loop:

    private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {
        try {
            for(Component component : cal.getComponents().getComponents("VTIMEZONE")) {
            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;
    }
    

    Even if I don't get the sense of some pieces of this code:

    Hope also these tips helps you to improve.