Operator overloading for collections?
Archie Cobbs
archie.cobbs at gmail.com
Tue Sep 2 15:52:53 UTC 2025
On Mon, Sep 1, 2025 at 5:13 PM Brian Goetz <brian.goetz at oracle.com> wrote:
> To shed some additional light on this, the argument here is not _only_
> philosophical. There is also a complexity and semantic argument against.
>
Personally I'm happy with the way things are but this is also an
interesting discussion.
The "complexity" and "semantic" counter-arguments are compelling but I'm
still missing something. It seems like those counter-arguments would be
(mostly) addressed by making the new operator feature merely "syntactic
sugar", like for-each loops and try-with-resources.
To give a concrete example, consider this proposal (this is just for
discussion! I am seeking understanding/clarification, not agreement)...
Consider an expression like a + b. Let A be the compile-time type of A, and
suppose A is not a primitive class.
Then a + b would compile if and only if the expression a.operatorPlus(b) would
compile - and it would have the exact same meaning.
Similarly, a + b * c << d would just be syntactic sugar for
a.operatorPlus(b.operatorTimes(c)).operatorLeftShift(d), etc. The rules
for precedence and evaluation order stay the same.
In other words, we declare that a + b and a.operatorPlus(b) are just
two different spellings of the same abstract concept (if it
exists, whatever it is)... so no need to differentiate between them. It's
just a new syntax for the same thing - if such a thing is defined.
Re: Complexity:
- Operator associativity and precedence does not change.
- "Ability to declare new signatures" - use method overloading to declare
multiple operatorPlus() variants taking different argument types
- "Applicability" and "resolving conflicts" - handled using the normal
method selection process.
- "...it wouldn’t be long before someone started saying 'and we’ll need to
control the precedence and associativity to make it make sense'" - Hard no!
Re: Semantics:
- "no one knows what + means without looking it up" - isn't that already
the case today?
- To understand a.foo(b) you must understand method A.foo(b)
- To understand a + b you must understand method A.operatorPlus(b)
The new methods allow arbitrary user code to participate, so they "grow the
language" in an open way.
I'm not saying there aren't still OTHER reasons not to add such a feature,
I'm just trying to narrow down what they are.
(Also, the question of whether, given this new feature, we would retrofit
existing collection classes is a completely separate (and possibly more
contentious) discussion.)
Thanks,
-Archie
--
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20250902/d20f0672/attachment.htm>
More information about the amber-dev
mailing list