This is from one question about lambda expression. I'm baffled with the syntax in line check((h, l) -> h > l, 0);
:
The check()
function requires a Climb object and an int. The line above does not provide any Climb object. And what does h > l, 0
mean?
interface Climb {
boolean isTooHigh(int height, int limit);
}
class Climber {
public static void main(String[] args) {
check((h, l) -> h > l, 0);
}
private static void check(Climb climb, int height) {
if (climb.isTooHigh(height, 1))
System.out.println("too high");
else
System.out.println("ok");
}
}
Your Climb
interface respects the contract of a functional interface, that is, an interface with a single abstract method.
Hence, an instance of Climb
can be implemented using a lambda expression, that is, an expression that takes two ints as parameters and returns a boolean in this case.
(h, l) -> h > l
is the lambda expression that implements it. h
and l
are the parameters (int
) and it will return whether h > l
(so the result is indeed a boolean
). So for instance you could write:
Climb climb = (h, l) -> h > l;
System.out.println(climb.isTooHigh(0, 2)); //false because 0 > 2 is not true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With