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?
2 Answers 2
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.
-
2Thanks for the answer and pardon my ignorance: I did not know that member variables and methods were allowed to have the same name. +1Giorgio– Giorgio2016年11月03日 17:29:09 +00:00Commented Nov 3, 2016 at 17:29
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.
-
1"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).mrr– mrr2016年11月03日 10:28:57 +00:00Commented Nov 3, 2016 at 10:28
-
1@MilesRout Indeed my answer is confusing, I have edited it to better clarify my thoughts.Spotted– Spotted2016年11月03日 10:44:48 +00:00Commented Nov 3, 2016 at 10:44