如何使用 Java 中的 lambda 從封閉類訪問變數?


由 lambda 表示式的封閉作用域定義的變數可以在 lambda 表示式中訪問。lambda 表示式可以訪問封閉定義的例項靜態變數和方法。它還可以訪問 "this" 變數(隱式和顯式),該變數可能是封閉類的例項。lambda 表示式還可以設定靜態例項變數的值。

示例

interface SimpleInterface {
   int func();
}
public class SimpleLambdaTest {
   static int x = 50;
   public static void main(String[] args) {
      SimpleInterface test = () -> x;     // Accessing of static variable using lambda
      System.out.println("Accessing static variable 'x': " + test.func());

      test = () -> {     // Setting the value to variable using lambda
         return x = 80;
      };
      System.out.println("Setting value for 'x': " + test.func());
   }
}

輸出

Accessing static variable 'x': 50
Setting value for 'x': 80

更新於:14-07-2020

712 瀏覽量

開啟你的職業生涯

透過學習課程,獲得認證

開始學習
廣告
© . All rights reserved.