Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet126/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   122   123   124   125   126   127   128   129   ...   245
Bog'liq
Java 17 Recipes

 How It Works
Lambda expressions can be assigned to variables of the same type as the implemented 
functional interface. Such expressions can contain a single-line expression or a 
multistatement body. Since the lambda expression can accept arguments, there are 
use cases for assigning such expressions to variables and then passing those variables 
into other objects to modify functionality. This pattern is useful for creating solutions 
containing more than one implementation. The solution to this recipe demonstrates this 
concept.
In the solution, the PassingLambdaFunctions class contains a calculate() method, 
which performs calculations on Double values passed into it as arguments. However, the 
calculate() method contains no calculation functionality at all. Rather, the calculation 
functionality is passed as an argument of type Function,Double> via 
a lambda expression. This type is one of the standard functional interfaces within 
the java.util.function package and the interface can be implemented by lambda 
expressions and then invoked later by calling its solo apply() method. Looking at the 
code in the calculate() method, the arguments contained within the Double[] are first 
added to a list. Next, lambda expression’s apply() method is invoked, passing the new 
list of values and returning a result into returnVal. Finally, returnVal is returned to the 
method invoker.
returnVal=f1.apply(varList);
return returnVal;
To implement the calculation functionality within the solution, lambda expressions 
are created in a separate class named MainClass. Each expression accepts a list of 
arguments and then calculates the values in the list, returning a result. For instance, the 
first lambda generated in MainClass calculates volume by multiplying together all of the 
values in the argument list and returning the result. This functionality is then assigned 
to a variable of type Function,Double>, and then it is passed into the 
PassingLambdaFunctions.calculate() method later on.
Any functionality can be implemented within a lambda expression and then passed 
around to different objects for use. This is an excellent way to promote code reuse and 
high maintainability.
ChapTer 6 LaMbda expressIons


234

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   122   123   124   125   126   127   128   129   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling