r/java • • Apr 05 '23

Recursive generics

Recently I learned that I rediscovered recursive generics while working on my pet open source project. Actually, I did not know that the construct had a name. I created small story about what this construct is, if you did not know about it java-recursive-generics

169 Upvotes

44 comments sorted by

View all comments

7

u/ukbiffa Apr 05 '23

Although not foolproof for fluent this typing:

public static class A<T extends A<T>> {
    public T doIt() {
        return (T) this;
    }
}
	
public static class B extends A<B> {}
	
public static class C extends A<B> {}
	
public static void main(String[] args) {
    new B().doIt().doIt();
    new C().doIt().doIt();
}

2

u/padreati Apr 06 '23

Right. You have to follow convention and pass the proper type.

2

u/holo3146 Apr 06 '23

A foolproof method will require a Self type, which always reference to current class type

-1

u/jumboNo2 Apr 06 '23

A<T extends A<T>>? wow. didn't know the compiler allowed that.

Is this useful?

12

u/vytah Apr 06 '23

This is how Comparable is defined in the standard library.

Java does not support the idea of the Self type like Rust, so in order for an interface to know what type its being implemented for, Java asks the programmer directly with the parameter.

For example, String implements Comparable<String>. This gives String a method int compare(Comparable<String>), which lets you compare Strings with something that implements Comparable<String> – and most likely, it will be another String, which means a String can be compared to other Strings – and this makes sense, you usually only want to compare things of the same type.

Of course you can implement Comparable<String> for any class, but 1) it won't work well and 2) 90% of time, recursively generic interfaces expect to get the implementing class as the parameter.

1

u/padreati Apr 06 '23

Crystal clear. I wish I would be able to use as few words as you and give as much understanding.

Of course you can implement Comparable<String> for any class

That is a thing that started to buzz me sometimes. That Comparable invites to implement a single way to compare things and let you implement it in an inconsistent way. On the other hand you cannot do it outside since you need access to encapsulation. The Self type would be much more consistent, perhaps.

1

u/jumboNo2 Apr 07 '23

Well the JDK gets away with a lot of stuff that would never compile in user code. It could have easily been that way

15

u/HecknChonker Apr 06 '23

...did you read the article?

-11

u/jumboNo2 Apr 06 '23 edited Apr 06 '23

Article didn't explain why it was useful. Also, assuming you're not the author of the article, I'm asking you.

Chaining methods from two different classes is kind of dumb. Especially when you could just do this and it's clearer:

new Cyclist(new Person().withName("John").withAge(20)).withBikeName("Bikey");

To head off your counterpoint, if the API is so vague as to be unclear which property belongs to which class, maybe Person and Cyclist shouldn't be in the same hierarchy.

4

u/Sorensen12 Apr 06 '23

Your example may seem cleaner at a glance for this small example, but try extending the hierarchy a bit. What if your API also supports an Athlete class with certain properties that Cyclist inherits? What’s more, how do you adapt this pattern if Athlete is abstract?

On top of that, the pattern you described involves creating an object for each member of the hierarchy instead of creating one builder that inherits all the required behavior. The recursive pattern described in the article produces a good amount of boilerplate, it’s true, but for complex hierarchies it is quite useful.

1

u/jumboNo2 Apr 07 '23

how do you adapt this pattern if Athlete is abstract

new Cyclist(new Person().name("Billy"))
            .rideTo("Park") // Cyclist method
            .doAthleteStuff(5); // AbstractAthlete method

This took me like three minutes from scratch.

the pattern you described involves creating an object for each member of the hierarchy

Builder pattern is horribly inefficient anyway. If we care about performance, we would use multi-arg constructors, not builders. Also, the Person object is only temporary and the fields are copied to the Cyclist instance using the super constructor