Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the following casting with method reference not produce a compilation error? [duplicate]

Tags:

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

like image 766
eitann Avatar asked Mar 08 '18 12:03

eitann


1 Answers

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.

like image 110
Michael Avatar answered Sep 19 '22 01:09

Michael