public class SomeClass{ public static int someFunction(int a) { return a; } public static void main(String[] args) { Consumer<Integer> c = SomeClass::someFunction; } }
I'm not getting why: Consumer<Integer> c = SomeClass::someFunction;
is not producing a compilation error, since the function someFunction is a method with return value, and Consumer is representing methods with no return value
From the spec:
If the body of a lambda is a statement expression (that is, an expression that would be allowed to stand alone as a statement), it is compatible with a void-producing function type; any result is simply discarded.
Same is true for method references.
It's more flexible that way. Suppose it was a compiler error to not use a return value when you called a method normally - that would be incredibly annoying. You'd end up having to use fake variables you didn't care about in some cases.
public class SomeClass { public static int someFunction(int a) { return a; } public static void main(String[] args) { someFunction(3); // "error" - ignoring return type int unused = someFunction(3); // "success" } }
If you want a the full formal definition of what is acceptable, see 15.13.2. Type of a Method Reference.
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