如何在 Java 中的 Lambda 表达式中使用 final 或有效地 final 的变量?
有效地 final 变量是指未显式声明为 final 但赋值后不能更改的局部变量。只有当局部变量是有效地 final 变量时,Lambda 表达式才可以在外部作用域中使用它们。。
语法
(optional) (Arguments) -> body
在下面的示例中,“size”变量未声明为 final,但它是有效地 final,因为我们没有修改“size”变量的值。
示例
interface Employee {
void empData(String empName);
}
public class LambdaEffectivelyFinalTest {
public static void main(String[] args) {
int size = 100;
Employee emp = name -> { // lambda expression
System.out.println("The employee strength is: " + size);
System.out.println("The employee name is: " + name);
};
emp.empData("Adithya");
}
}输出
The employee strength is: 100 The employee name is: Adithya
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP