简体   繁体   中英

Java generics, wildcards, collections: compilation error

Given the following class:

import java.util.ArrayList;
import java.util.Collection;

public class Main {

    private static class A {
    }

    private static class B<T> {
        private void thenReturn(T value) {
        }
    }

    private static <T> B<T> when(T methodCall) {
        return new B<T>();
    }

    private static Collection<? extends A> method() {
        return new ArrayList<>();
    }

    public static void main(String[] args) {
        Collection<? extends A> result = new ArrayList<>();
        // Does not compile.
        when(method()).thenReturn(result);
    }

}

I get the compilation error The method thenReturn(Collection<capture#1-of ? extends Main.A>) in the type Main.B<Collection<capture#1-of ? extends Main.A>> is not applicable for the arguments (Collection<capture#3-of ? extends Main.A>) The method thenReturn(Collection<capture#1-of ? extends Main.A>) in the type Main.B<Collection<capture#1-of ? extends Main.A>> is not applicable for the arguments (Collection<capture#3-of ? extends Main.A>)

What have I to change in the main method in order that it will compile? Is there a better solution than

    public static void main(String[] args) {
        Collection result = new ArrayList<>();
        when(method()).thenReturn(result);
    }

This works to get around it - it looks like the capture rules get a bit stretched for long expressions.

    Collection<? extends A> result = new ArrayList<>();
    B<Collection<? extends A>> when = when(method());
    when.thenReturn(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM