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.)
-
1I really wouldn't recommend naming methods the same as your class...Broots Waymb– Broots Waymb2015-10-22 15:19:44 +00:00Commented Oct 22, 2015 at 15:19
-
1Also, here is a C# answer, but it closely applies to Java as well: stackoverflow.com/questions/160118/…Broots Waymb– Broots Waymb2015-10-22 15:21:14 +00:00Commented Oct 22, 2015 at 15:21
-
1stackoverflow.com/q/21873829/2711488Holger– Holger2015-10-22 16:15:18 +00:00Commented Oct 22, 2015 at 16:15
Add a comment
|
1 Answer
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);