4

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");
  }
}
0

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

How can a boolean be cast to a Climb object in the call to check()? I don't understand.
@FukuzawaYukio sound like you aren't familiar with lambda expressions implementing functional interfaces. Go learn about it :).
1

(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.

3 Comments

How come (h,l) -> h>l is the Climb object? I can only see that it's a boolean and a boolean cannot be cast to a Climb object.
@FukuzawaYukio the lambda (h, l) -> h > l can be (and is) interpreted as the funtional interface Climb as it matches boolean isTooHigh(int height, int limit);
It's a lambda with a boolean as its return type. In the end, that's all a Climb object is, a function from two ints to a boolean. Java apparently has special syntactic sugar to convert such lambdas to anonymous implementations of an interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.