为什么编译器拒绝访问lambda中的非最终变量 [英] Why does the compiler deny access to non-final variables inside a lambda

查看:46
本文介绍了为什么编译器拒绝访问lambda中的非最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚看到此问题,显然Java应该拒绝对lambda表达式主体内的非最终变量的访问.为什么?

I just saw this question, and apparently it's obvious that Java should deny access to non-final variables inside the body of a lambda expression. Why?

例如,我不明白为什么以下代码有害:

for example, I don't see why the following code is harmful:

String[] numbers = new String[10]; // put some numerical strings in
BigInteger sum = new BigInteger("0");
numbers.forEach(n -> sum = sum.add(new BigInteger(n)));

推荐答案

Lambda只是语法糖,它们被编译为匿名内部类.匿名内部类由于其范围而不能使用 non-final 局部变量.这是解释:

Lambdas are just syntactic sugar and they get compiled into anonymous inner classes. Anonymous inner classes can't use non-final local variables because of their scope. Here's the explanation:

该方法的局部变量存在于堆栈中,并且仅存在在该方法的整个生命周期中.您已经知道局部变量仅限于声明该变量的方法.该方法结束时,堆栈框架被吹走,并且变量是历史.但是即使方法完成后,内部类如果在其中创建的对象仍然可以在堆上保持活动状态,例如,对它的引用被传递到其他代码中,然后存储在实例变量中.因为局部变量不是只要方法本地的内部类对象保证有效,内部类对象不能使用它们.除非局部变量是标记为最终!

The local variables of the method live on the stack, and exist only for the lifetime of the method. You already know that the scope of a local variable is limited to the method the variable is declared in. When the method ends, the stack frame is blown away and the variable is history. But even after the method completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an instance variable. Because the local variables aren't guaranteed to be alive as long as the method-local inner class object, the inner class object can't use them. Unless the local variables are marked final!

礼貌:SCJP 6凯西·塞拉(Kathy Sierra)和贝特·贝茨(Bert Bates)的学习指南

Courtesy: SCJP 6 Study guide by Kathy Sierra and Bert Bates

这篇关于为什么编译器拒绝访问lambda中的非最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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