如何在 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

更新於:2020 年 7 月 10 日

2K+ 次瀏覽

開拓您的職業

完成課程,獲得認證

立即開始
廣告