Why Java Doesn't Need Operator Overloading (and Very Few Languages Do, Really)
Christopher Wright
dhasenan at gmail.com
Wed Apr 15 16:45:02 PDT 2009
Don wrote:
> Paul D. Anderson wrote:
>> Sounds like someone needs a strong dose of D!!
>>
>> http://java.dzone.com/articles/why-java-doesnt-need-operator
>>
>> The comments bounce between "operator overloading is always bad
>> because you can do idiotic things with it" and "operator overloading
>> is essential because sometimes you really need it".
>>
>> How about a language where operator overloading is available for the
>> cases where you do really need it, but isn't available in general?
>>
>> Hmmm...
>>
>> Paul
> He says he doesn't like it because:
>
> The number of operators that you can overload is very small and each of
> them is attached to very specific semantics that makes little sense
> outside the realm of scalars and of a few other specialized mathematical
> concepts (e.g. matrices).
>
> Bingo! That's what operator overloading is for. **Don't overload
> arithmetic operators unless you are doing arithmetic.** I think the main
> problem with operator overloading in C++ is that that point wasn't
> explained well at all. The D spec could probably do a better job of it,
> but at least the ~ operator removes the temptation for people to use +
> to mean concatenation.
This reminds me of something I did at work. C# 2.0 has no builtin syntax
for associative arrays, and we needed to create a lot of dictionaries of
string -> object. We came up a little class with operator overloads:
operator[string,object] added a dictionary entry and returned the
dictionary builder. But when you're done with that, you still need to
convert to a dictionary. So we added an operator overload for this.
Now we format strings like:
_formatter.Format("${hello} ${world}", -Using.Values["hello",
helloObject]["world", worldObject]);
More information about the Digitalmars-d
mailing list