1

I stumble upon this problem million of times and I can't wrap my head around it.

Let's assume I have a stream seq of type Stream<? extends T> and I want to execute a forEach on its elements.

The type of the consumer now becomes a Consumer<? super ? extends T>, now how does java treat a generic type ? super ? extends T ?

Is it the equivalent of ? super T, because the generic type ? extends T is considered as a T in this example.

Someone please provide the exact procedure of how the java compiler treats the following situations.

marsouf
  • 1,107
  • 8
  • 15
  • I think it's equivalent to `? super T`. If you have a `Stream extends Number>`, `Consumer` would be invalid, but `Consumer` and `Consumer` should still be applicable. Shouldn't be hard to test. – shmosel Sep 05 '17 at 22:43
  • The type of the consumer is, in reality, `? super U`. where `U`==`? extends T`. In effect for code, this is similar to `? super T`, since you're accepting a contravariant bound of something which extends `T`. Look up "covariance vs contravariance". – Rogue Sep 05 '17 at 22:43
  • @Rogue I will for sure – marsouf Sep 05 '17 at 22:46
  • The type of the `Stream` is capture converted for the purpose of considering the parameter type to `forEach`, so the parameter type to `forEach` actually becomes something like `Consumer super CAP#1>` where `CAP#1` is the result of capture conversion on the type argument `? extends T`. I explained capture conversion in [another answer here](https://stackoverflow.com/a/46061947/2891664) and TBH I don't really feel like writing another capture conversion answer today. Capture conversion is the "real" answer. – Radiodef Sep 05 '17 at 22:54

0 Answers0