Callable<Void> as Functional Interface with lambdas

ferrerverck picture ferrerverck · Jun 24, 2014 · Viewed 12k times · Source

I am just learning about new java8 features. And here is my question:

Why is it not allowed to use Callable<Void> as a functional interface for lambda expressions? (Compiler complains about returning value) And it is still perfectly legal to use Callable<Integer> there. Here is the sample code:

public class Test {
    public static void main(String[] args) throws Exception {
        // works fine
        testInt(() -> {
            System.out.println("From testInt method"); 
            return 1;
        });

        testVoid(() -> {
            System.out.println("From testVoid method"); 
            // error! can't return void?
        });
    }

    public static void testInt(Callable<Integer> callable) throws Exception {
        callable.call();
    }

    public static void testVoid(Callable<Void> callable) throws Exception {
        callable.call();
    }
}

How to explain this behavior?

Answer

Thilo picture Thilo · Jun 24, 2014

For a Void method (different from a void method), you have to return null.

Void is just a placeholder stating that you don't actually have a return value (even though the construct -- like Callable here -- needs one). The compiler does not treat it in any special way, so you still have to put in a "normal" return statement yourself.