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?
Interface Callable<V> This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With