Hacker News new | ask | show | jobs
by ethzero 4835 days ago
It's not an identical capability. Scala doesn't technically have operator overloading, it has symbolic method names and operator syntax for methods. This means you can use any valid name as an operator.

With C++, you can only overload the built-in symbolic operators. This means instead of choosing the best symbolic name to use as an operator you're forced to re-purpose some built-in operator like "<<". In Scala you can pick any name or symbol you want.

2 comments

Yes I know that, but the point is that the "operator overloading is terrible" complaint typically cites either plainly daft straw men like "what if someone overrides + to mean subtraction", or else hones in on << for streams, which as others have pointed out here is actually perfectly readable and sensible. I have yet to see a single sensible criticism that holds water (OK, MS overloading address-of & on a smart pointer, that one was stupid ..)

Conversely, there was an XML library for Scala posted on Reddit about a year ago that used things like <:<, <<? and <> as method names; clearly the freedom to concoct your own symbolic names is far more open to abuse than the oft-maligned C++ mechanism.

Two big problems with overloading << for streams are operator precedence (the precedence of << makes little sense for a stream operator) and the fact that the chained syntax can make the whole thing ambiguous (which is kind of a subset of the precedence problem), e.g.: cout << x << 3, does that shift x by 3, or output x and 3 separately?
Same with Haskell, which makes it compact but not always very readable (it effectively turns many libraries into their own non-intuitive DSL).