Void is not a functional interface

Viewed 3255

I am trying to subscribe observable like :

List<String> colors = Arrays.asList("RED", "BLACK", "WHITE", "GREEN", "YELLOW", "BROWN", "PURPUL", "BLUE");
    Observable.just(colors).subscribe(s -> System.out.println(s));

It's working fine but if I use method reference compiler gives error "void is not a functional iterface"

Any one can explain little bit deep? As per me subscriber accept consumer functional interface, which doesn't return anything but we can print stream data like :

 Observable.just(colors).subscribe(s -> System.out::println);// NOT COMPILE
3 Answers

Your method reference syntax is wrong. Change it like so,

Observable.just(colors).subscribe(System.out::println);

Just the following is enough:

Observable.just(colors).subscribe(System.out::println);

While writing the method reference, you don't have to mention the arg before that.

The 'subscriber' method takes Consumer (a functional Interface) as an argument which has one abstract method void accept(T t). So here we can pass the lambda expression.

As we know 'println' returns void so we can use this here.

subscribe(s -> System.out.println(s)); will give us the correct output. but if we want to write it as a method reference then no need to give the argument 's' as println method. this is how method reference syntax typically is, in java.

Related