Java Generic Type with wildcard extends class

Viewed 37

I try to use BiConsumer in Java to do an addition, which accepts all Number type. My code is as follow:

public class App {
    public static void main(String[] args) {
        BiConsumer<? extends Number, ? extends Number> addition = (a, b) -> {
            Double sum = a.doubleValue() + b.doubleValue();
        };
        addition.accept(1, 2.3);
    }
}

But it will have compiler error as below when I call the accept method in BiConsumer:
enter image description here

The accept method has a simple method signature as below:
void accept(T t, U u);
I am not familiar with Generic, can anyone explain why we cannot do so? If it is invalid, why doesn't the compiler indicates when I declare ? extends Number in the BiConsumer.
And what is the proper why to achieve my goal?

0 Answers
Related