Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
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
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
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 |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling