0

I don't really know if this is possible but I've been trying to accept a Consumer<? extends Event> for a while, but I keep getting a variable mismatch whenever invoking it.

Here is my example code:

public static void main(String[] args) {
    ArrayList<Consumer<? extends Event>> x = new ArrayList<>();
    Consumer<ExampleEvent> y = e -> {}; // ExampleEvent extends Event
    x.add(y);
    for (Consumer<? extends Event> z : x) {
        z.accept(new Event());
    }
}

Every time I get an error saying that it's an argument mismatch

I'm using eclipse on windows

here is the error: The method accept(capture#5-of ? extends Event) in the type Consumer<capture#5-of ? extends Event> is not applicable for the arguments (Event)

Bwookzy
  • 3
  • 2
  • You should read about PECS (producer extends consumer super) – Clashsoft May 28 '18 at 20:00
  • Also read: [generics are invariant in Java](https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po/2745301#2745301). – MC Emperor May 28 '18 at 20:13

2 Answers2

0

This code won't work because you are passing in arguments of the wrong type. y in this case is a Consumer<ExampleEvent>, which means that the signature of its accept override would be:

void accept(ExampleEvent e);

When you call z.accept(new Event()) you are passing in an object of the wrong type. Event is not a subclass of ExampleEvent.

Kayla C.
  • 11
  • 4
0

Imagine if z is of type SubEvent. Where SubEvent extends Event. In this case, the call z.accept(new Event()) is wrong. The method accept() expects a parameter of type SubEvent or its subclasses, not superclasses.

Ahmad Shahwan
  • 1,662
  • 18
  • 29