Link to static vs non-stationary method

I wondered how to distinguish between references to static and non-static methods with the same name. In my example, I have a class called StringCollectorthat 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 Stream<String>to collect a list of strings, I would write something like this:
Arrays.asList("a", "b", "c").stream()
.collect(StringCollector::new, StringCollector::append, StringCollector::concat);
As we can see, the code does not compile. I think that since the compiler cannot decide which method to use, because each of them will correspond to the functionality. The question is: is there any possible way to refer to various static methods from references to instance methods?

(PS: Yes, the code compiles if I rename one of the two methods. For each of them.)

+4
source share
1 answer

In this case, an unbound reference to the instance method appendhas the same arity, argument types, and even the return value as a reference to a static method append, so no, you cannot resolve the ambiguity for method references. If you do not 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 really want to use the static method:

collect(StringCollector::new, (sb, s) -> StringCollector.append(sb, s),
        StringCollector::concat);
+6
source

Source: https://habr.com/ru/post/1612778/


All Articles