Search code examples
javagenericsbuilder

Is it legal to make a type parameter recursive for an already generic class?


If I have a class:

class Foo<T> {}

Is it legal / does it make sense to do this?

class Foo<T, R extends Foo<T, R>> {}

For context, I am trying to implement this pattern for a Builder that already has one generic parameter.


Solution

  • I`m not sure, if I'm properly getting your additional question in your comment. But let's try to explain.

    The class with what you call "recursive parameter" is definitely legal and it makes sense.

    It's used in "extendable" builders. Let's see following example:

    public interface BaseBuilder<T, B extends BaseBuilder<T,B> {
        B add(String field, String value);
    
        default B person(String firstName, String lastName) {
            // This chaining is only possible thanks to that recursive parameter
            return add("firstName", firstName).add("lastName", lastName);
        }
    
        T build();
    
        default T buildPerson(String firstName, String lastName) {
            return person(firstName, lastName).build();
        }
    }
    

    You re-use this e.g. like this:

     public interface MyBuilder<T> extends BaseBuilder<T, MyBuilder<T> {}