java - Method reference static vs non static -
i've wondered how distinct between static , non static method references same name. in example have class called stringcollector
has following 3 methods:
stringcollector append(string string)
static stringcollector append(stringcollector stringcollector, string string)
stringcollector concat(stringcollector stringcollector)
if want use stream<string>
collect list of strings write that:
arrays.aslist("a", "b", "c").stream()
.collect(stringcollector::new, stringcollector::append, stringcollector::concat);
can see code doesn't compile. think that's because compiler can't deside, method use because each of them match functional. question now: there possible way distinct static method references instance method references?
(ps: yes code compiles if rename 1 of 2 methods. each of them.)
in case unbound reference instance method append
has same arity, argument types , return value reference static method append
, no, cannot resolve disambiguation method references. if don't want rename 1 of methods, should use lambda instead:
collect(stringcollector::new, (sb, s) -> sb.append(s), stringcollector::concat);
or if want use static method:
collect(stringcollector::new, (sb, s) -> stringcollector.append(sb, s), stringcollector::concat);
Comments
Post a Comment