noncom
noncom

Reputation: 4992

Java generic inference is too broad?

I have 2 classes:

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));
    }
}

and

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)));
    }
}

However, the compiler says at o.walk(walker, accF, acc, level + 1) that inference variable T has incompatible bounds: equality constraints: T upper bounds: A, Object, RR

Why so and how do I fix this?

Upvotes: 1

Views: 69

Answers (1)

Thomas
Thomas

Reputation: 88707

That's some really complex code and I don't have the time to really think about it, but since getChildren() returns any M and N#walk uses its own generic definitions the compiler knows that e.g. A could be a different type with different boundaries for the children and walk.

You might try to put the generic definitions at class level, e.g.

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(...) { ... }
}

Upvotes: 1

Related Questions