Mark
Mark

Reputation: 2227

How to implement a generic recursive interface?

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?

Upvotes: 2

Views: 704

Answers (1)

Eran
Eran

Reputation: 393791

You can declare it as follows:

class SuperImpl implements SuperInter<SuperImpl> {

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

Upvotes: 2

Related Questions