r/javahelp • • Feb 03 '20

Syntactic sugar: static references to instance methods?

Hello!

I found the following thing a little bit strange. Consider the following class:

class Example{

  public void foo(int x){

  }

  public void bar(){
    
  }
}

Now I can make an object, get a method reference to an instance method and then use it.

Example e = new Example();

Consumer<Integer> ex = e::foo;

ex.accept(4);

Method foo(int x) is clearly a Consumer<Integer>. How ever, I have no idea why the following works:

Consumer<Example> ex2 = Example::bar;

ex2.accept(new Example()); 

First, it refers to Example::bar in a static way, even though it is an instance method.

Secondly, Consumer<Example> means it consumes Example -objects, which implies there is a method accept(Example e). But Example::bar is clearly not a Consumer<Example>

I guess the

Consumer<Example> a = Example::bar; 

is translated to following:

Consumer<Example> a = (x) -> x.bar();

I could not find this anywhere in the tutorial or any other article that would explain it. I'd think that if syntactic sugar like this exists, where's the documentation?

22 Upvotes

1 comment sorted by

10

u/GuyWithLag Feb 03 '20

First, it refers to Example::bar in a static way, even though it is an instance method.

No; it is a method reference expression which refers to the set of methods named bar in the Example class. Now, there are some applicability schenanigans that I'm not smart enough to explain, but the gist is that the reference is converted to the target type given by the assignment, and one of the criteria is the number of arguments used to filter the set of potential methods; in the JLS is stated that

Two different arities, n and n-1, are considered, to account for the possibility that this form refers to either a static method or an instance method.

So, it's looking at both static and non-static methods. Further down the text:

A method reference expression of the form ReferenceType ::
[TypeArguments] Identifier can be interpreted in different ways. If Identifier refers to an instance method, then the implicit lambda expression has an extra parameter compared to if Identifier refers to a static method. It is possible for ReferenceType to have both kinds of applicable methods, so the search algorithm described above identifies them separately, since there are different parameter types for each case.

So, non-static methods get converted to a lambda that has an extra parameters that acts as this (in the context of the virtual lambda expression that is created for that method reference).