Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 type inference with non-static access of static members

Consider the following code:

class Test {

    void accept(Consumer<Integer> c) {}

    static void consumer(Integer i) {}

    void foo() {
        accept(this::consumer); // The method accept(Consumer<Integer>) in the type Test is not applicable for the arguments (this::consumer)
        accept(Test::consumer); // Valid
    }

}

I came across this the other day when accidentally calling a static method in a non-static way. I know that you shouldn't call static methods in a non-static way, but I am still wondering, why isn't it possible to infer the type in this case?

like image 419
sqrooty Avatar asked May 08 '15 20:05

sqrooty


1 Answers

Actually error says invalid method reference static bound method reference.

Which makes sense if you know about four types of methods references:

  1. Reference to a static method.
  2. Reference to a bound non-static method.
  3. Reference to an unbound non-static method.
  4. Reference to a constructor

JLS explanation:

It is a compile-time error if a method reference expression has the form ReferenceType :: [TypeArguments] Identifier, and the compile-time declaration is static, and ReferenceType is not a simple or qualified name

In addition to bad design there is performance overhead for capturing (bounding) the receiver.

like image 131
user2418306 Avatar answered Oct 12 '22 13:10

user2418306