3 ms·
Java's decision to privilege "primitive" types was a failure of imagination. They decided they didn't want operator overloading but didn't make any way to repla
by JulianMorrison 11y ago
Java's decision to privilege "primitive" types was a failure of imagination. They decided they didn't want operator overloading but didn't make any way to replace it.
They should retrofit it as follows:
interface Addable<T> {
T add(T other);
}
And then make the + apply to any Addable, which can be defined for the boxed primitives. And so on for the other operators.
- Jtsummers 11y agoIt's been a while since I Java'd, but wouldn't this still have problems when mixing types? A java string added to anything results in the toString() method being called. It doesn't matter if the string is before or after the + operator. How do you specify precedence in this new scheme short of an exponentially large `add` method handling all the cases. And each add method has to handle all the variety of cases.
- Kristine1975 11y agoMake it: interface Addable<RHS, Result> { Result add(RHS other); } The problem is hardly new though. Groovy is very Java-like and has operator overloading: http://groovy-lang.org/operators.html#Operator-Overloading http://groovy-lang.org/operators.html#Operator-Overloading
- andreasvc 11y agoWould be best to disallow mixing types I think, except for the legacy behavior with primitive types you describe. Those hidden conversions are a source of subtle bugs.