How it works...

If a functional interface is written to simply return an object through instantiation, with or without the presence of constructor argument(s), we can use a constructor reference to implement its abstract method. This simplifies the implementation of a lambda expression by having the class name of the object concatenated to two colons (:) followed by the new keyword. The createEmployee() method uses a constructor reference to implement a Supplier that will provide an empty Employee object. For some classes that require constructor parameters to instantiate, convertBday() shows us that the constructor reference is feasible for creating the object. But there is only one case where we cannot push this short-hand form, and that is when the constructor of the class throws any exceptions (risky constructor).

The constructor reference is one special type of method reference that refers to a constructor of a class. A method reference replaces the common lambda expression form as long as the functional interfaces are satisfied with the result of the method that is not considered risky.

The method reference can also be applied to a typical instance and static methods, too. The convertInt() method depicts the replacement of the curly braces form with in the Integer::parseInt statement. The parseInt() method is a static method of the int wrapper class, which is one of the best candidates for this short-hand form. Likewise, any instance method can be subject to a method reference, just like in the midYearStarted() method, wherein a certain employment start date is verified. In this method, the Predicate is implemented using a method reference to the method before() of the Date object. A method reference to an instance method requires an instance object of the class needed to implement the functional interface.

The method reference is not always applicable to all technical requirement, thus the original lambda form is still suggested for implementing functional interfaces.

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

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