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
Apparently, (h, l) -> h > l
is a lambda expression where the result is of a boolean type and the 0
is the second argument of check
, which is unrelated to the lambda expression itself; the 0
does not belong to the lambda expression as such.
(h, l) -> h > l
is the climb object. It is a lambda that returns true when the first argument (h) is greater than the second (l). 0
is the int, and the comma separates the arguments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.