使用有界泛型编译lambda时出错

时间:2018-01-21 04:55:33

标签: java generics lambda

以下是我创建的一个设计的,自包含的示例,用于演示我遇到的一个更复杂的程序问题:

@RequestMapping(value = "/Home/PopulateVisits", method = RequestMethod.POST)
    public @ResponseBody List<DataCollectionForm> PopulateVisits(DataCollectionForm dataCollectionForm, HttpServletRequest request) {

这不编译:

public class MyTest {
    public static void main(String[] args) {
        SubObject[] array = new SubObject[5];
        Iterator<? extends SuperObject> iterator 
                = Arrays.asList((SuperObject[]) array).iterator();
        Iterable<? extends SuperObject> iterable = () -> iterator;
    }
}

class SuperObject {};

class SubObject extends SuperObject{};

我知道我可以简化通用,将MyTest.java:9: error: incompatible types: bad return type in lambda expression Iterable<? extends SuperObject> iterable = () -> iterator; ^ Iterator<CAP#1> cannot be converted to Iterator<SuperObject> where CAP#1 is a fresh type-variable: CAP#1 extends SuperObject from capture of ? extends SuperObject 替换为<? extends SuperObject>。但这会破坏我在更大的计划中的目的。为什么会出现这个错误?

1 个答案:

答案 0 :(得分:2)

感谢@ Radiodef的评论,我能够解决这个问题。正如https://docs.oracle.com/javase/tutorial/java/generics/capture.html中所解释的那样,技巧是使用辅助函数:

public class MyTest4 {
    public static void main(String[] args) {
        SubObject[] array = new SubObject[5];
        Iterator<? extends SuperObject> iterator
                = Arrays.asList((SuperObject[]) array).iterator();
        Iterable<? extends SuperObject> iterable = getIterable(iterator);
    }

    static <T> Iterable<T> getIterable(Iterator<T> iterator) {
        return () -> iterator;
    }

}

class SuperObject {};

class SubObject extends SuperObject{};