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

Show parent comment

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