Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callable<Void> as Functional Interface with lambdas

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?

like image 533
ferrerverck Avatar asked Jun 24 '14 07:06

ferrerverck


People also ask

Is callable interface a functional interface?

Interface Callable<V> This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

Is lambda function callable?

In Java 8, Callable interface has been annotated with @FunctionalInterface . Now in java 8, we can create the object of Callable using lambda expression as follows.

Why do I need a functional interface to work with lambdas?

Surely lambda expression can be one-time used as your commented code does, but when it comes to passing lambda expression as parameter to mimic function callback, functional interface is a must because in that case the variable data type is the functional interface.


1 Answers

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.

like image 175
Thilo Avatar answered Sep 30 '22 03:09

Thilo