在 Java 中,我們可以在lambda表示式中訪問哪些型別的變數?


lambda 表示式由兩部分組成,一部分是 引數 另一部分是 表示式 並且這兩部分已由箭頭 (->) 符號分隔開。lambda 表示式可訪問其 封閉範圍內的變數。

Lambda 表示式可以訪問它所包圍類的 例項靜態 變數,並且還可以訪問 區域性 變數,這些變數是 實際最終最終 的。

語法

( argument-list ) -> expression

示例

interface TestInterface {
   void print();
}
public class LambdaExpressionTest {
   int a; // instance variable
   static int b; // static variable
   LambdaExpressionTest(int x) {    // constructor to initialise instance variable
      this.a = x;
   }
   void show() {
      // lambda expression to define print() method
      TestInterface testInterface = () -> {
      // accessing of instance and static variable using lambda expression
         System.out.println("Value of a is: "+ a);
         System.out.println("Value of b is: "+ b);
      };
      testInterface.print();
   }
   public static void main(String arg[]) {
      LambdaExpressionTest test = new LambdaExpressionTest(10);
      test.show();
   }
}

輸出

Value of a is: 10
Value of b is: 0

更新於: 2019-12-11

886 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.