lambda表达式中使用的变量应该是final或者有效的final [英] Variable used in lambda expression should be final or effectively final

查看:12039
本文介绍了lambda表达式中使用的变量应该是final或者有效的final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


lambda表达式中使用的变量应该是final或者有效的最终

Variable used in lambda expression should be final or effectively final

当我尝试使用 calTz 它显示此错误。

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


推荐答案

A final 变量意味着它只能被实例化一次。使用Java中的
,你不能在lambda和匿名内部类中使用非final变量。

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.

你可以使用旧的for-重构你的代码每个循环:

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:


  • 你调用 v.getTimeZoneId(); 而不使用其返回值

  • ,分配 calTz = TimeZone.getTimeZone(v.getTimeZoneId()。getValue()); 你不修改原来的传递 calTz 并且你不在这个方法中使用它

  • 你总是返回 null ,为什么不设置 void 作为返回类型?

  • 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.

这篇关于lambda表达式中使用的变量应该是final或者有效的final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆