Limitations of forEach with instance method references in Java 8

Viewed 9828

Assume I have the following functional interface:

public interface TemperatureObserver {
    void react(BigDecimal t);
}

and then in another class an already filled-in ArrayList of objects of type TemperatureObserver. Assuming that temp is a BigDecimal, I can invoke react in a loop using:

observers.forEach(item -> item.react(temp));

My question: can I use a method reference for the code above?

The following does not work:

observers.forEach(TemperatureObserver::react);

The error message is telling me that

  1. forEach in the Arraylist observers is not applicable to the type TemperatureObserver::react
  2. TemperatureObserver does not define a method react(TemperatureObserver)

Fair enough, as forEach expects as an argument a Consumer<? super TemperatureObserver>, and my interface, although functional, does not comply to Consumer because of the different argument of react (a BigDecimal in my case).

So can this be solved, or it is a case in which a lambda does not have a corresponding method reference?

3 Answers
Related