java Error---Lambda expression's local variable e cannot re-declare another local variable defined e

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Miha_Singh/article/details/83001437

在使用lambda表达式时,为控件添加事件响应函数时,出现:

Lambda expression's local variable e cannot re-declare another local variable defined e

出错的代码段如下:

stage.setOnCloseRequest(e->{
						...
						...
					});

从错误提示可以看出是对e进行了重复的声明,检查代码,发现果然在代码中有这样一段:

btn.setOnAction(e->{
					stage.show();
				});

所以,很简单,只要把e换成别的名字就好了!但是在查解决方案时在Oracle官网发现了更为权威的的解释:

Local Variables in Lambda Expressions
A lambda expression does not define a new scope; the lambda expression scope is the same as the enclosing scope. For example, if a lambda expression body declares a local variable with the same name as a variable in the enclosing scope, a compiler error—Lambda expression’s local variable i cannot re-declare another local variable defined in an enclosing scope—gets generated, as shown in Figure 3.
oracle

官网的解释:lambda表达式不定义新范围, lambda表达式作用域与封闭作用域相同。例如,如果lambda表达式主体声明一个与封闭范围中的变量同名的局部变量,这个时候就需要使用其他的变量名。

猜你喜欢

转载自blog.csdn.net/Miha_Singh/article/details/83001437