Reputation: 518
Is there a way to get the compiler to choose the static method reference?
This code fails to compile because there are two methods that satisfy this method reference. Is there a way to hint or cast it so that it resolves the static method reference?
public class Number {
private final int value;
public Number(int value) {
this.value = value;
}
public Number add(int x) {
return operate(Number::add, x); // <---- compile fail here at Number::add
}
private Number operate(BiFunction<Number, Integer, Number> function, int x) {
return function.apply(this, x);
}
public static Number add(Number x, int y) {
return new Number(x.value + y);
}
}
Upvotes: 3
Views: 4246
Reputation: 1778
There is no "collision" :)
The issue is that Number::add
is ambiguous (the compiler - the one in eclipse, at least - reports that correctly).
The ambiguous code:
BiFunction<Number, Integer, Number> m = Number::add;
could either mean:
BiFunction<Number, Integer, Number> m = (x,y) -> Number.add(x,y);
or:
BiFunction<Number, Integer, Number> m = (x,y) -> x.add(y);
Upvotes: 5