Why is it legal to pass a method reference of one parameter as an argument of expected type BiConsumer
whose abstract method requires two arguments?
Example:
class Experiment {
private String name;
public Experiment(String name) {
this.name = name;
}
public void oneParamMethod(Object o) {
System.out.println(this.name + " and " + o);
}
public <T, S> void executeBiConsumer(BiConsumer<T, S> biCon, T in1, S in2) {
biCon.accept(in1, in2);
}
public static void main(String[] args) {
// notice that the name is "INSTANCE", but it won't be printed out
Experiment exp = new Experiment("INSTANCE");
// executeBiConsumer expects a functional of two params but is given a method
// reference of one param. HOW IS THIS LEGAL?
exp.executeBiConsumer(Experiment::oneParamMethod, new Experiment("PARAM"), 999);
}
}
Output:
PARAM and 999
Let's change the invocation such that the second argument is not an instance of Experiment
as follows:
exp.executeBiConsumer(Experiment::oneParamMethod, new String("INVALID"), 999);
Now, it won't compile.
- Why does the code compile without complain if the second argument is an
Experiment
instance, and why does it not compile otherwise? - Why is it valid to pass a method reference of only one parameter as an argument that expects
BiConsumer
?