user2454455
user2454455

Reputation:

Why <? extends Number> not working for Integer?

Why

Predicate<? super Integer> isGreaterThanZero = num -> num.intValue() > 0;

works for

isGreaterThanZero.test( new Integer( 2 ));

and not

Predicate<? extends Number> isGreaterThanZero = num -> num.intValue() > 0;

I see them as the same since Integer is-a Number

Upvotes: 8

Views: 595

Answers (1)

Misha
Misha

Reputation: 28133

When you declare Predicate<? extends Number> isGreaterThanZero, you are telling the compiler that isGreaterThanZero is a Predicate parametrized by some unknown subtype of Number.

As far as the compiler knows, it could be a Predicate<Double> or a Predicate<BigInteger>. Can you safely pass an Integer to test(Double x) or to test(BigInteger x)? You cannot. The only thing that you can safely pass to test method of Predicate<? extends Number> is null.

If you want isGreaterThanZero to be a predicate that works on any subtype of Number, you should declare it as Predicate<Number>.

Upvotes: 13

Related Questions