Why does the following code not compile.
Consumer con = (s) -> System.out::println;
It says
The target type of this expression must be a functional interface
even though Consumer is a Functional Interface. The below works just fine.
Consumer con2 = (s) -> {System.out.println(s);};
The parentheses for specifying the parameter can be omitted for a single-parameter lambda expression. The target type of the lambda expression—the functional interface ActionListener —is inferred from the context, which is a method invocation.
The type of System. out. println is not a functional interface, since System.
No, all the lambda expressions in this code implement the BiFunction<Integer, Integer, Integer> function interface. The body of the lambda expressions is allowed to call methods of the MathOperation class. It doesn't have to refer only to methods of a functional interface.
Runnable, ActionListener, Comparable are some of the examples of functional interfaces.
By now you may have guessed that resolving this error " the target type of this expression must be a functional interface " means functional interface should have only one abstract method. So we need to delete the second method.
Java 8 - The target type of this expression must be a functional interface. Java 8 Error-The target type of this expression must be a functional interface. If you are working in Java 8 and getting the following compilation error – to a reference which is not a Functional Interface. .
Thus the functional interface specifies its target type. As you can see Functional interface is an interface with only one abstract method and lambda expression provides implementation of the abstract method defined by the functional interface.
A functional interface is an interface with only one abstract method. A functional interface is also known as SAM type where SAM stands for (Single Abstract Method). Lambda expression is an instance of the functional interface and provides implementation of the abstract method defined by the functional interface.
Because that's a method reference, the usage is a bit different:
Consumer<String> c = System.out::println;
The argument that the consumer takes (s
) will be still passed to the println
method.
here is Oracle's tutorial on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With