Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
How It Works
Lambda expressions have access to the variables located within the enclosing class. Thus, a lambda expression contained within a class method can access any instance variables of the enclosing class. No additional scope is added to a lambda expression, so it can access fields, methods, and local variables of the enclosing scope. In the solution, the lambda expression contained within the lambdaInMethod() method can access all of the fields that are declared within either class. This is because both the inner and outer classes enclose the lambda. One thing to note is that if an inner class contains an instance variable of the same name as a variable that has been declared in the outer class, then the lambda uses the variable of its enclosing class. Therefore, in the solution, the InnerClass CLASSA field is accessed from within the lambda expression rather than the outer class reference. Local variables referenced from within a lambda expression must be either final or effectively final. An error occurs when a lambda expression attempts to access a variable that was changed within the context of an enclosing method. For instance, suppose that the method in the solution was changed to the following. void lambdaInMethod(String passedIn) { String METHODA = "Method-level A"; passedIn = "test"; Consumer System.out.println(x); System.out.println("CLASSA Value: " + CLASSA); System.out.println("METHODA Value: " + METHODA); System.out.println(passedIn); }; l1.accept(CLASSA); l1.accept(passedIn); } Note that the string passed into lambdaInMethod() is assigned a new value just before the lambda expression is invoked. Therefore, the passedIn variable is no longer effectively final, and lambda expressions cannot introduce a new scope level. Consequently, the lambda expression does not have access to the passedIn variable from within the context of the expression. ChapTer 6 LaMbda expressIons |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling