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

3

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.