I am going through Java 8 Feature and using Jshell to explore it. I tried to run the below command:
Consumer<String> consumer = (str)->System.out::println;
But it failed with the below error:
Error: | incompatible types: bad return type in lambda expression | void is not a functional interface
I didn’t get exactly what’s the issue Consumer takes one argument and return nothing. Same I am doing here by passing 1 arg str and printing. So what’s the issue with this syntax.
If you want a
Consumer<String> that prints the string given to it, it’s either a lambda expression calling
Consumer<String> consumer = (str)->System.out.println(str);
or a method reference to
Consumer<String> consumer = System.out::println;
but not both. You seem to have mixed up the syntax.
str -> System.out::println would be a lambda expression that takes in an object, ignores it, and returns a method reference to
System.out::println. You can for example do:
Function<Object, Consumer<String>> func = str -> System.out::println;
but such indirectness is very uncommon.