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

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

问题描述

lambda 表达式中使用的变量应该是 final 或有效 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;
}

推荐答案

final 变量意味着它只能被实例化一次.在 Java 中,您不能在 lambda 以及匿名内部类中重新分配非最终局部变量.

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.

您可以使用旧的 for-each 循环重构您的代码:

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 并且你不会t 在这个方法中使用它
  • 你总是返回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 表达式中使用的变量应该是最终的或有效的最终的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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