Search code examples
javagenericslambdacovariancemethod-reference

How to pass a method reference to a covariant parameter


Given we have the following classes an methods:

class Fruit {}
class Orange extends Fruit {}

void process(Consumer<? extends Fruit> action) {}
void eatOnlyOranges(Orange evt) {}

This compiles without warning.

    Consumer<Orange> consumer = this::eatOnlyOranges;
    process(consumer);

I want to allow this, but it doesn't compile?

    process(this::eatOnlyOranges);

Can I change the signature of process(Consumer<? extends Fruit> action) to make it work?

NOTE: Please assume that the implementation of process(..) will check if the given Consumer can handle the given Fruit. This detail is not relevant for this question.


Solution

  • Besides @EmersonCod's answer, changing the method signature to

    <T extends Fruit> void process(Consumer< T > action) {
        // ...
    }
    

    seems to do the job.