An example of lambda parameters

The following is an example to demonstrate how you can use an _ (underscore) to mark unused lambda parameters. The following code uses the BiFunction<T, U, R> functional interface which can accept two arguments (T and U), and returns a value of the type R:

BiFunction<Integer, String, Boolean> calc = (age, _) -> age > 10;

In the preceding example, since the lambda expression assigned to the BiFunction functional interface uses just one of the method parameters (that is, age), JEP 302 proposes using the underscore to mark the unused parameter.

The following code highlights a few use cases to illustrate how you would use the same code without the convenience of marking unused lambda parameters (the comments state the value that the code is passing to the unused parameter):

// Approach 1
// Pass null to the unused parameter
BiFunction<Boolean, Integer, String> calc = (age, null) -> age > 10;

// Approach 2
// Pass empty string to the unused parameter
BiFunction<Boolean, Integer, String> calc = (age, "") -> age > 10;

// Approach 3
// Pass ANY String value to the unused parameter -
// - doesn't matter, since it is not used
BiFunction<Boolean, Integer, String> calc =
(age, "Ban plastic straws") -> age > 10;


// Approach 4
// Pass any variable (of the same type) to the unused parameter -
// - doesn't matter, since it is not used
BiFunction<Boolean, Integer, String> calc = (age, name) -> age > 10;
A lot of other functional programming languages use a similar notation to mark unused parameters.
..................Content has been hidden....................

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