Java 8 Function<String, Void> vs Consumer<String> [duplicate]
Asked Answered
D

1

8

I can't for the life of me find an explanation of the following:

public static void takesAFunction(Function<String, Void> func) {
    func.apply("Hi I'm running a function");
}

public static void takesAConsumer(Consumer<String> func) {
    func.accept("Hi I'm running a consumer");
}

public static void main(String[] args) throws Exception {
    takesAFunction((String str) -> { System.out.println(str); });
    takesAConsumer((String str) -> { System.out.println(str); });
}

I'm using JDK 1.8.0_66 and the line

takesAFunction((String str) -> { System.out.println(str); });

is marked as an error saying that

The method takesAFunction(Function<String,Void>) in the type MyClass 
is not applicable for the arguments ((String str) -> {})

I can't understand how is

Function<String, Void> 

different from

Consumer<String>

when both return nothing and both take in a single String parameter.

Can someone pls shed some light on this cos it's killing.

Thanks in advance!

Dimorph answered 16/12, 2015 at 15:53 Comment(2)
You aren't returning a Void value.Quickel
Similarly, there is a difference between Runnable and Callable<Void> as Void is a reference to a class which can only be null (Unless you use reflection to create one)Kenyon
O
13

A Function<String, Void> should have the following signature:

Void m(String s);

not to be confused with void m(String s);!

So you need to return a Void value - and the only one available is null:

takesAFunction((String str) -> {
  System.out.println(str);
  return null;
});

compiles as expected.

Oleate answered 16/12, 2015 at 15:55 Comment(1)
Oh got it - thanks a ton!Dimorph

© 2022 - 2024 — McMap. All rights reserved.