1、lambda表達式可存取外部本地final變數
final int num = 1; Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num); stringConverter.convert(2); // 3
2、與存取本地變數相反,成員變數和靜態變數可以透過lambda表達式讀寫。這種存取變數的方式也實作在匿名變數中:
class Lambda4 { static int outerStaticNum; int outerNum; void testScopes() { Converter<Integer, String> stringConverter1 = (from) -> { outerNum = 23; return String.valueOf(from); }; Converter<Integer, String> stringConverter2 = (from) -> { outerStaticNum = 72; return String.valueOf(from); }; } }
以上是怎麼用java Lambda存取變數的詳細內容。更多資訊請關注PHP中文網其他相關文章!