Java泛型推断过于宽泛?

时间:2016-06-06 12:52:54

标签: java generics recursion lambda type-inference

我有2个班级:

class M {
    public <R, A, T extends A> A walk(BiFunction<Widget, Integer, Stream<R>> walker, BiFunction<A, Stream<R>, T> accF, A acc, int level) {
        return accF.apply(acc, walker.apply(this, level));
    }
}

class N extends M {

    public Stream<M> getChildren() {return Stream.of(new M()...);}

    @Override
    public <RR, A, T extends A> T walk(BiFunction<Widget, Integer, Stream<RR>> walker, BiFunction<A, Stream<RR>, T> accF, A acc, int level) {
        return accF.apply(accF.apply(acc, walker.apply(this, level)), getChildren().map(o -> o.walk(walker, accF, acc, level + 1)));
    }
}

然而,编译器在o.walk(walker, accF, acc, level + 1)inference variable T has incompatible bounds: equality constraints: T upper bounds: A, Object, RR

为什么会这样,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

这是一些非常复杂的代码,我没有时间真正考虑它,但是因为getChildren()返回任何MN#walk使用自己的通用定义,编译器知道那个,例如A可以是不同类型,具有不同的孩子边界和walk

您可能会尝试将通用定义放在类级别,例如

class M <R, A, T extends A> { 
  public  A walk(...) { ... }
}

class N <RR, A, T extends A> extends M< RR, A, T> { 
  public Stream<M<RR, A, T>> getChildren() {...}
  public  A walk(...) { ... }
}