-3

As you all know we engineers works best at nights :) I was studying lambdas at yesterday night and I saw a piece of code like that,

    BirdCompare tester = new BirdCompare();
    MathOperation addition = (a, b) -> (a + b);
    MathOperation subtraction = (int a, int b) -> (a - b);
    MathOperation multiplication = (int a, int b) -> {
        return a * b;
    };
    MathOperation division = (a, b) -> a / b;

    interface MathOperation {
        int operation(int a, int b);
    }

The sample simply assigned lambda expression to MathOperation interface's variable but how ? It makes a implementation of method named operation which is in the interface and the point I was confused is assignment of that implementation to the variable of interface. I really wonder the idea based on this approach. Thank you in advance to all.

1 Answers1

1

You can assign a lambda expression to a functional interface type that is congruent -- that is, types of parameters and the return type match. Please see the JLS, Section 15.27.3 for the exact details, but essentially:

A lambda expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.

The JLS, Section 9.8, defines a functional interface:

A functional interface is an interface that has just one abstract method (aside from the methods of Object), and thus represents a single function contract.

It doesn't matter that your MathOperation interface isn't built-in to Java, and it doesn't matter that it isn't annotated with @FunctionalInterface. It has one abstract method, and the parameter and return types match, so it qualifies.

rgettman
  • 176,041
  • 30
  • 275
  • 357