8

I often wonder why Java uses :: for method references instead of ., e.g. why write

  System.out::println

instead of

  System.out.println

Of course, one might simply answer: "because the designers decided so". On the other hand, I would have expected the second syntax because the dot is the usual Java syntax for accessing class members.

So is there any known special reason for introducing the new :: syntax instead of using the existing . convention for method references?

20

This is to avoid ambiguity in case if class has (static) member with the same name as method (Java allows that).

It is easy to see from code snippet in Java tutorial about method references:

Because this lambda expression invokes an existing method, you can use a method reference instead of a lambda expression:

Arrays.sort(rosterAsArray, Person::compareByAge);

If class Person in above snippet would also have member named compareByAge (of the type appropriate to pass to Arrays.sort), dot notation wouldn't allow to tell whether parameter refers to method or member.

  • 2
    Thanks for the answer and pardon my ignorance: I did not know that member variables and methods were allowed to have the same name. +1 – Giorgio Nov 3 '16 at 17:29
3

They introduced a new syntax because the behaviour is not the same.

The . means that you want to get a reference on the function in order to invoke it right after.

When you use method reference (::) you want to store a reference on the function but you don't want to invoke it right away.

A more practical aspect is how would you differentiate between a public attribute and a method having the same name with the . ? You simply can't. With :: there is no more ambiguity.

  • "The . means invoking the function, literally executing it's code." No, the dot means accessing the member. The parentheses mean invoking the function in languages with C-style syntax (like Java). – Miles Rout Nov 3 '16 at 10:28
  • 1
    @MilesRout Indeed my answer is confusing, I have edited it to better clarify my thoughts. – Spotted Nov 3 '16 at 10:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.