… no, don’t tell me you like Perl. Because you don’t. You never did. It does horrible things. It makes your code look like…
Designing Perl 6 as found on the awesome Perl Humour page
Perl made heavy use of operator overloading and used operators for a variety of things. A similar tendency can be seen in C++ and Scala. See also people comparing the two. So what’s wrong with operator overloading?
People never agreed whether Scala got operator overloading right or wrong:
Operator overloading can be good, but mostly isn’t. In Java, we’re all missing better ways to interact with BigDecimal and similar types:
// How it is:
bigdecimal1.add(bigdecimal2.multiply(bigdecimal3));
// How it should be:
bigdecimal1 + bigdecimal2 * bigdecimal3
Of course, operator precedence would take place as expected. Unlike C++ or Scala, ideal operator overloading would simply map common operators to common method names. Nothing more. No one really wants API developers to come up with fancy ##-%>> operators.
While Ceylon, Groovy, and Xtend implemented this in a somewhat predictable and useful way, Kotlin is probably the language that has implemented the best standard operator overloading mechanism into their language. Their documentation states:
Binary operations
Expression
Translated to
a + b
a.plus(b)
a – b
a.minus(b)
a * b
a.times(b)
a / b
a.div(b)
a % b
a.mod(b)
a..b
a.rangeTo(b)
That looks pretty straightforward. Now check this out:
We’ve recently blogged about Ceylon’s awesome language features. But the above Kotlin features are definitely a killer and would remove any other sorts of desires to introduce operator overloading in Java for good.
Let’s hope future Java versions take inspiration from Kotlin, a language that got operator overloading right.