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

-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/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