Woe is me for using ? super T in a method call (part 1)
Zhong Yu
zhong.j.yu at gmail.com
Sun Mar 2 21:53:06 PST 2014
Wildcard capture works on the 1st level wildcard:
a List<? extends String> object is a List<x>, for some x that x<:String
It does not work on deeper levels:
a List<List<? extends String>> object is NOT a List<List<x>> for some x.
In your example, we'll need
Consumer<? super T> <: Consumer<E>
no choice of E can make that happen.
The solution is to almost always use wildcard on co/contra-variant types:
internalTake(Consumer<? super E>[] c)
The problem of the solution is that our code is litterred with
wildcards (in a very ugly notation no less)
Zhong Yu
On Sun, Mar 2, 2014 at 8:08 AM, Timo Kinnunen <timo.kinnunen at gmail.com> wrote:
> Hi,
>
>
>
>
> These examples used to compile in ECJ until recently and I didn't bat an eyelid at them, but not anymore. Looks like they haven't compiled in javac for maybe lot longer.
>
>
>
>
> The first one is just precious in its simplicity:
>
>
>
>
> private static <E> void internalTake(Consumer<E>[] c) {}
>
> public static <T> void take(Consumer<? super T>[] c) {
>
> internalTake(c);//error?
>
> }
>
>
>
>
> Wow, WTF? Just pick one super-type of T, any one!
>
>
>
>
> Here's a more fully-fledged motivating example:
>
>
>
>
> private static void callerOfTake2() {
>
> take2(
>
> "A test string",
>
> asArray(
>
> (CharSequence s) -> System.out.println(s),
>
> (String s) -> System.out.println("S" + s),
>
> (Object s) -> System.out.println("O" + s)));
>
> }
>
> @SafeVarargs
>
> private static Consumer<? super String>[] asArray(Consumer<? super String>... cees) {
>
> return cees;
>
> }
>
> static <T> void take2(T t, Consumer<? super T>[] c) {
>
> internalTake2(t, c);//error?
>
> }
>
> private static <SUB_E extends E, E> void internalTake2(SUB_E e, Consumer<E>[] c) {
>
> for(Consumer<E> consumer : c) {
>
> consumer.accept(e);
>
> }
>
> }
>
>
>
>
>
> So what's going on here? Javac's explanation doesn't really explain where the disconnect is between my understanding of how these wildcards should work and how they actually work.
>
>
> I'm splitting the other example to another email because this is getting long enough already.
>
>
> --
> Have a nice day,
> Timo.
>
> Sent from Windows Mail
>
More information about the lambda-dev
mailing list