0

I can't find an answer so... I have read the post Difference between <? super T> and <? extends T> in Java and understood that instance of List<? super Number> can return only Object type and that is true. But if I try to use a super wildcard with Consumer like this

Consumer<? super Number> consumerNum = n -> System.out.println("number " + (n.intValue() + 200));

Variable n is Number not Object! Why? I can't understand.

  • Wow, I'm surprised that type-inference allows that! I would have guessed that the compiler would complain that it can't tell what the lambda's type should be. (But if the compiler is going to accept it, `Number` definitely seems to make more sense than `Object`. Can you clarify why you expect the latter?) – ruakh Dec 28 '21 at 06:37
  • Because of the following: What type of object are you guaranteed to receive when you read from `List super Integer> foo3`: 1) You aren't guaranteed an `Integer` because `foo3` could be pointing at a `List` or `List`. 2) You aren't guaranteed a `Number` because `foo3` could be pointing at a `List`. 3) The only guarantee is that you will get an instance of an `Object` or subclass of `Object` (but you don't know what subclass). – D Garus Dec 28 '21 at 08:04
  • In addition to distinguishing a *consumer* from a *list*, you also need to distinguish the code that *fulfills* the contract from the code that *relies on* the contract. Note that `Consumer super Number> consumer = numberConsumer` is totally valid when `numberConsumer` implements `Consumer`, because `Number` *is* a supertype of `Number`. – ruakh Dec 28 '21 at 10:14

0 Answers0