Callable<Void> as Functional Interface with lambdas

12,999

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.

Share:
12,999
ferrerverck
Author by

ferrerverck

Updated on June 05, 2022

Comments

  • ferrerverck
    ferrerverck almost 2 years

    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?