compareTo and deriving

Brian Goetz brian.goetz at
Mon Dec 4 15:20:56 UTC 2017

Let's not forget that compareTo() got much easier to implement with the 
advent of the Comparator factories in Java 8:

     static final Comparator c
         = Comparators.comparing(Foo::int).thenComparing(Foo::bar);

     public int compareTo(T other) { return, other); }

On 12/4/2017 10:12 AM, forax at wrote:
> ----- Mail original -----
>> De: "Brian Goetz" <brian.goetz at>
>> À: "Remi Forax" <forax at>, "amber-spec-experts" <amber-spec-experts at>
>> Envoyé: Lundi 4 Décembre 2017 15:54:13
>> Objet: Re: compareTo and deriving
>> As you might remember from the EG meeting, we have toyed with a notion
>> of "method builders" which would be a more declarative way to declare
>> template-izable methods.  The intent all along was that, once we have
>> such a mechanism, records would just be a consumer of such a mechanism.
>> That said, such a mechanism is bigger both from a technical perspective
>> and a bikeshed perspective.  90% of the current OO-ceremony-pain is in
>> ctors, Object methods, and accessors.  So my preference would be to nail
>> down the semantics of data classes first, and then explore whether it
>> makes sense to surface a more general mechanism.
> I'm trying to propose a middle ground (not too far from only support Object methods) to allow to not have too much couple between the JLS and the metafactory methods.
> One advantage i see to have compareTo generated is that most implementation i see of the compareTo are broken either because of the primitive overflowing or compareTo and equals not having compatible semantics. One problem we will have if we let people to write compareTo is that it will be harder to get it right because equals will be generated while compareTo will be written manually without seeing the code of equals.
> Rémi
>> On 12/4/2017 8:34 AM, Remi Forax wrote:
>>> Ok,
>>> record/data class currently provides getters and toString/equals/hashCode, what
>>> if i want to add a compareTo.
>>> In Haskell, it's easy, one can use 'deriving', in Java, it can be written that
>>> way,
>>>     record Point(int x, int y) implements Comparable<Point>
>>>       deriving equals, hashCode, toString, compareTo;
>>> For the compiler, the method exists in the supertypes, so the signature of the
>>> method can be computed from the super types,
>>> after each generated method use an invokedynamic with the same meta protocol (a
>>> list of getters),
>>> so if by convention "equals", "hashCode", "toString", "compareTo" are the names
>>> of some bootstrap methods in a class DerivingMetaFactory,
>>> it can be trivial for a JDK developer to add a new bootstrap method without
>>> having to change the JLS.
>>> So my point is, that we can specify once how the compiler should generate codes
>>> for any generated methods in an extensible way.
>>> regards,
>>> Rémi

More information about the amber-spec-experts mailing list