When using the double colon operator to refer to an overloaded method, Java does not seem to be able to determine the correct method to use. Consider this example:
public class A {
private void setter(final Number value) { }
private void setter(final Optional<Number> value) { }
private void setter2(final Optional<Number> value) { }
private <T> void useSetter(final Consumer<Optional<T>> a) { }
private void callMethod() {
useSetter(this::setter); // Error here
useSetter(this::setter2);
}
}
The first call to useSetter
does not compile and gives the following errors:
Cannot infer type argument(s) for <T> useSetter(Consumer<Optional<T>>)
The type A does not define setter(Optional<Object>) that is applicable here
However, the second call compiles just fine, which means that the problem is in the overloading of setter
. Only one of the setter
overloads is applicable, so I don't understand why this doesn't work.
It is possible to get around this by using a lambda that specifies the parameter type, but that's a lot more verbose.
useSetter((final Optional<Number> v) -> setter(v));
Is there a better way to handle this situation or am I stuck working around this strange quirk?