[英]lambda expression and global variables
I just started working around lambda expression in Java 8. I'm bit confused about effectively final
. 我刚刚开始研究Java 8中的lambda表达式。我对
effectively final
感到有些困惑。
Local variable initialized once is effectively final
but what about global variable, I can change value of global variable and use it in lambda expression. 一次初始化的局部变量
effectively final
是effectively final
变量,但是全局变量呢,我可以更改全局变量的值并在lambda表达式中使用它。 So what is the reason behind local variable should be effectively final
. 那么局部变量应该
effectively final
的原因是什么。 I couldn't find any articles or on javadoc about this. 我找不到关于此的任何文章或在javadoc上。
import java.util.ArrayList;
import java.util.List;
public class Main {
private String lastname = "Thakor";
public static void main(String[] args) {
Main objMain = new Main();
objMain.test();
}
public void test(){
List<String> listStrings = new ArrayList<String>();
listStrings.add("Vicky");
listStrings.add("Thakor");
String middlename = "V";
//Local variable middlename defined in an enclosing scope must be final or effectively final
/* middlename = "T";*/
/**
* In case of global variable, why lambda expression not throwing error...
* Local variable middlename defined in an enclosing scope must be final or effectively final
*/
lastname = "T";
listStrings.stream()
.forEach(firstname ->{
System.out.println("Firstname: " + firstname);
System.out.println("Middle: " + middlename);
System.out.println("Lastname: " + lastname);
System.out.println("--------------------------------------");
});
}
}
Output 产量
Firstname: Vicky
Middle: V
Lastname: T
--------------------------------------
Firstname: Thakor
Middle: V
Lastname: T
--------------------------------------
When you reference a "global" variable in a lambda, you're really capturing a reference to this
, which is effectively final. 当您在lambda中引用“全局”变量时,实际上是在捕获
this
的引用, this
实际上是最终的。
Consider the following snippet (untested): 考虑以下代码片段(未经测试):
class Main {
class Box {
int value;
}
void foo() {
Box box = new Box();
Runnable r = () -> box.value++;
}
}
Even though you're changing the box.value
, you're doing it through the box
reference, which is effectively final. 即使您要更改
box.value
, box.value
通过box
引用来完成,实际上是最终的。 Similarly, you code is equivalent to 同样,您的代码等效于
System.out.println("Lastname: " + this.lastname);
meaning you're accessing lastname
through the this
reference, which is effectively final. 表示您正在通过
this
引用访问lastname
,实际上是最终名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.