The target type of this expression must be a functional interface in MethodReferences

HariJustForFun picture HariJustForFun · Feb 23, 2017 · Viewed 44.2k times · Source

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

Answer

Eugene picture Eugene · Feb 23, 2017

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.