I thought that parameter and wildcard placeholder roughly has same meaning, where the first one is for defining classes and methods and the second is for declaring variables. But apparently it is not the case.
import java.util.List;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer<List<? extends Number>> l1 = null;
Consumer<List<? extends Number>> l2 = null;
l1 = l2; // compiles
}
static <T extends Number> void m(Consumer<List<T>> l) {
Consumer<List<? extends Number>> l3 = l; // doesn't compile
}
}
I thought that line Consumer<List<? extends Number>> l3 = l
should work just as l1 = l2;
. But it is not the case. Can someone explain why this sample doesn't compile and how can I workaround this.
> l2` though it's not obvious be me why this doesn't work.
– Peter Lawrey Jan 05 '18 at 14:41> l can be a list of anything however, Consumer
– John Kane Jan 05 '18 at 14:47> l3 is much more specific.
> l2 = (Consumer) l;` but is there some way to make it work without creating/suppressing a warning?
– Artem Petrov Jan 05 '18 at 14:49>?`
– Turing85 Jan 05 '18 at 14:56>` does not match `Consumer
– VGR Jan 05 '18 at 16:42>`. Wildcard matching is not recursive; it only applies to the topmost level of a wildcard.
> l3 = (Consumer
– Bohemian Jan 05 '18 at 17:50>)(Consumer)l; // compiles`
> l3 = (Consumer)l;`
– Artem Petrov Jan 05 '18 at 17:54> l` is treated as `Consumer
– Artem Petrov Jan 05 '18 at 17:57>` and not as `Consumer
>`?