Stefan Ram said:
I a sense, there is another overload.
Some programmers (ab)use the "+" operator to convert
to java.lang.String, as in:
"" + 2
instead of
java.lang.String.valueOf( 2 )
So "+" could mean:
- numerical addition,
- string concatenation, or
- conversion to string.
At the bytecode level, + is very heavily overloaded. It could be integer
addition, or long addition, or double precision floating point addition, or
single precision floating poitn addition. At the "Java" level, we usually
gloss over that, and just consider all those operations to be the same (even
though the algorithm could vary wildly, for example between integral
addition and floating point addition).
The "string concatenation" and "conversion to string" isn't two
different overloaded operations. Actually, when you do the string
concatenation, string conversion always occurs. So for example, the express
"Hello " + "world" converts its arguments to strings (which is trivial since
they are both already strings), and then does the concatenation.
However, I have no problem with all this. Human natural
languages tend to overload nearly every word with different
meanings, and polymorphism in OOP also might be considered as
some kind of "overloading" of a name with many ("poly")
implementations ("morphs").
So if it is used in natural languages and in OOP, why
should it be a problem when used for some operators?
1 + 1 + " foo" == "2 foo"
"foo " + 1 + 1 == "foo 11"
If you follow the rule of least astonishment, the above behaviour
shouldn't happen, because most people would be surprised by it. Why are they
surprised? Because they are confusing when + is performing numerical
addition and when it is performing string concatenation.
I'm not saying ALL operator overloading is bad; I'm just saying that
overloading an operator to perform both numerical addition and string
concatenation can lead to surprising behaviour.
- Oliver