2

I tried to wrap my head around a problem I cannot seem to find an answer for. Consider the following 2 examples:

{
    // this works.
    Consumer<CharSequence> c = F -> {};
    test(c);
}
static void test(Consumer<? super String> c) { /* content */}

and:

{
    // doesn't compile
    List<Consumer<CharSequence>> list = new ArrayList<>();
    test(list);
}
static void test(List<Consumer<? super String>> list) { /* content */ }

There might be a valid reason why the second example is not compiling/type-safe, but I cannot find/deduct this reason. So any help in clarifying this is appreciated.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
n247s
  • 1,898
  • 1
  • 12
  • 30
  • 1
    you need `List extends Consumer super String>>` which is a parent for `List>` – Andrew Tobilko Jan 05 '19 at 13:41
  • @Andrew Tolbilko I had to think thrice about that one, but that would make sence. But what if you want this method to accept both `List` and `List>` (since I would only add to it)? for the first you would use `super` instead of `extends`, but that would break the second one. Or is it just not possible to let it accept both? – n247s Jan 05 '19 at 14:07
  • `List extends Object>` would work for it, they are too different types, so it's impossible to find a closer parent – Andrew Tobilko Jan 05 '19 at 14:16
  • I found a better alternative (altough it isn't a short one) : `static > void test(List super T> list);` – n247s Jan 12 '19 at 12:37

0 Answers0