I see code like this:
1 2 3 4 5 6 7 8 9
Here is the code in “Utils.java”:
1 2 3 4
“request -> log(request)” is a lambda expression, but how does it become a “Consumer”?
The answer is ”Java Lambda Type Inference”. In short it means:
One lambda expression may map to different functional interface types depending on the context.
The compiler infers the type of a lambda expression.
Conceptually ”Functional interface” is an interface has exact one abstract method.
The process of inferring the type of a lambda expression is called target typing. The compiler uses the following rules to determine whether a lambda expression is assignable to its target type:
It must be a functional interface.
The parameters of lambda expression must match the abstract method in functional interface.
The return type from the lambda expression is compatible with the return type from the abstract method in functional interface.
The checked exceptions thrown from the lambda expression must be compatible with the declared throws clause of the abstract method in functional interface.
The code below is an example of the Lambda type inference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
One more thing about “@FunctionalInterface” (from here) is that:
The compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.
So the functionality of the “@FunctionalInterface” annotation is to generate compiling error if the annotated interface is not a functional interface and improve readability, not a grammar prerequiste of a functional interface.