2

Another case of java generics confusion...

I am defining a hierarchy of interfaces which must include a method to return a list of that interface type. This is a standard use case for the recursive generic pattern (or whatever the name for this is):

interface SuperInter<T extends SuperInter<T>> {
    List<T> getEffects();
}

Now when I extends this interface:

interface SubInter extends SuperInter<SubInter> {}

I can implement the sub-interface and have the correct method to implement:

class SubImpl implements SubInter {

    @Override
    public List<SubInter> getEffects() {
        return null;
    }
}

and similarly any other interface which uses itself as the generic type will have its implementing class contain a method that returns a list of that interface.

However, I can't implement the super interface type correctly:

class SuperImpl implements SuperInter<SuperInter> {

    @Override
    public List<SuperInter> getEffects() {
        return null;
    }
}

Besides raw types warning, I get:

Bound mismatch: The type SuperInter is not a valid substitute for the bounded parameter <T extends SuperInter<T>> of the type SuperInter<T>

I guess because the class does not extends itself. How can I achieve this?

1
  • i might be wrong, but due to the recursion the only right way to write is is the following: class SuperImpl implements SuperInter<SuperInter<SuperInter<SuperInter<SuperInter<[to infinity]>>>> { Commented Jul 28, 2017 at 6:00

1 Answer 1

2

You can declare it as follows:

class SuperImpl implements SuperInter<SuperImpl> {

    @Override
    public List<SuperImpl> getEffects() {
        return null;
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

So I can't have the interface returned like in the subclass/interface case, only the implementing class?
Try having it return List<? super T>
(In your deleted answer to this other question you can use the two-arg overload of Comparator.comparing.)
@StuartMarks i don't understand what this relates to. Also do you know the answer to my comment?
@Mark Re your question/comment, offhand no, but I'll post if I think of anything.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.