How it works...

The formalization of lambda expressions in Java 1.8 is all documented in JSR 335, which covers the @FunctionalInterface annotation to create custom functional interfaces, built-in functional interfaces, and Stream APIs with lots of useful mapping, sorting, filtering, reduction, and aggregate methods. But what is most important is the recognition of anonymous functions which have the following form:

() -> { System.out.println("lambda expression"); } 

The left-hand side of the arrow symbol is the area of inferred parameters and the right-hand side is the body of the anonymous function which can be a simple expression or a block of statements. An anonymous function is technically a reduced lambda expression.

In this form, the lambda expression is said to be implementing the correct interface method when its parameters and return types match the abstract method. If the abstract method has zero parameters, just like in getEmployees(), the left-hand side of the expression remains empty. But in the case of updateSalary(), where there are two double parameters, the lambda expression must contain two local variables at the left-hand side, which are inferred to be double types. Since these two methods output a value, a return statement must be found in their respective implementation body bearing the value of the function. And if the implementation requires a more complex and lengthy logic, the body part of this form can still be treated as a typical anonymous inner class where variables and constants are declared and initialized, just like what is emphasized in updateSalary().

This new syntax of lambda expression has nothing to do with the existence of the @FunctionalInterface annotation. The use of this annotation is only to restrict one interface to have only one abstract method, otherwise, a compilation error will be issued by the compiler. Moreover, the use of the annotation @FunctionaInterface allows us to add more methods to our interfaces, namely the default and static methods, which are allowed by Java 1.7 and above.

The default methods are instance-scoped methods that become available once the lambda expression of the said @FunctionalInterface has been successfully implemented. They are defined by the keyword default.

Unlike in a normal interface, static methods can now be created in @FunctionalInterface and can be accessed at interface level. Functional interfaces can have more than one default or static method. The ComputeSalaryIncrease interface contains one default and one static method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.233.43