Variable used in lambda expression should be final or effectively final

后端 未结 7 835
抹茶落季
抹茶落季 2020-11-22 07:54

Variable used in lambda expression should be final or effectively final

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

7条回答
  •  野性不改
    2020-11-22 08:36

    A final variable means that it can be instantiated only one time. in Java you can't use non-final 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:

    • you call a v.getTimeZoneId(); without using its return value
    • with the assignment calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue()); you don't modify the originally passed calTz and you don't use it in this method
    • You always return null, why don't you set void as return type?

    Hope also these tips helps you to improve.

提交回复
热议问题