在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP