I'm learning about Method References from Java 8 and I have difficulties understanding why does this work?
class Holder {
private String holded;
public Holder(String holded) {
this.holded = holded;
}
public String getHolded() {
return holded;
}
}
private void run() {
Function<Holder, String> getHolded = Holder::getHolded;
consume(Holder::getHolded); //This is correct...
consume(getHolded); //...but this is not
}
private void consume(Consumer<Holder> consumer) {
consumer.accept(null);
}
As you can see in run
method - Holder::getHolded
returns unbound method reference which you can invoke by passing object of type Holder
as an argument. Like this: getHolded.apply(holder)
But why it casts this unbound method reference to Consumer
when it is invoked directly as an method argument, and it does not doing it when I'm passing Function
explicitly?