Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of lambda expression syntax is this in Java 8?

Tags:

java

lambda

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");
  }
}
like image 200
Max Avatar asked Feb 08 '23 12:02

Max


1 Answers

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
like image 159
Alexis C. Avatar answered Feb 19 '23 14:02

Alexis C.