4

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.)

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

1 Answers1

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