I've wondered how to distinct between static and non static method references with the same name. In my example I have a class called StringCollector
that has the following three methods:
StringCollector append(String string)
static StringCollector append(StringCollector stringCollector, String string)
StringCollector concat(StringCollector stringCollector)
Now if I want to use a Stream<String>
to collect a list of strings I would write something like that:
Arrays.asList("a", "b", "c").stream()
.collect(StringCollector::new, StringCollector::append, StringCollector::concat);
As we can see the code doesn't compile. I think that's because the compiler can't deside, which method to use because each of them would match the functional. The question is now: Is there any possible way to distinct static method references from instance method references?
(PS: Yes the code compiles if I rename one of the two methods. For each of them.)
Asked
Active
Viewed 140 times
4

Tagir Valeev
- 97,161
- 19
- 222
- 334

Vincent Reinthal
- 91
- 6
-
1I really wouldn't recommend naming methods the same as your class... – Broots Waymb Oct 22 '15 at 15:19
-
1Also, here is a C# answer, but it closely applies to Java as well: http://stackoverflow.com/questions/160118/static-and-instance-methods-with-the-same-name – Broots Waymb Oct 22 '15 at 15:21
-
1http://stackoverflow.com/q/21873829/2711488 – Holger Oct 22 '15 at 16:15
1 Answers
6
In this case unbound reference to the instance method append
has the same arity, argument types and even return value as the reference to the static method append
, so no, you cannot resolve the disambiguation for method references. If you don't want to rename one of the methods, you should use lambda instead:
collect(StringCollector::new, (sb, s) -> sb.append(s), StringCollector::concat);
Or if you actually want to use static method:
collect(StringCollector::new, (sb, s) -> StringCollector.append(sb, s),
StringCollector::concat);

Tagir Valeev
- 97,161
- 19
- 222
- 334