Community
Participate
Working Groups
Operators such as "+" and "*" are commutative, i.e. (x + y) == (y + x) Right now we have scenarios where only one direction works: "string" + 123 // works 123 + "string" // error, incompatible types It would be nice to have extension methods so that "+" and "*" behave commutative. Another option could be to annotate an operator to be commutative. This would make the operator implicitly available a second time with swapped LHS and RHS.
Since operators are just aliases for method invocations. Their implementation contract does not specify whether they are commutative, may cause side effects, symetry and the like. That's why I don't like the idea to automagically swap arguments or something. Though, having an ObjectExtension operator_plus(Object, String) sounds appealing to me.
(In reply to comment #1) > Since operators are just aliases for method invocations. Their implementation > contract does not specify whether they are commutative, may cause side effects, > symetry and the like. That's why I don't like the idea to automagically swap > arguments or something. not automagically, one could annotate a method with "@Commutative".
Can you give an example where this would be useful?
(In reply to comment #3) > Can you give an example where this would be useful? To support 3.14 + 123 and 123 + 3.14 you currently need two methods: operator_plus(BigDecimal left, BigInteger right) operator_plus(BigInteger left, BigDecimal right) since the addition on numbers is commutative, both methods would have to do the same. with @Commutative operator_plus(BigDecimal left, BigInteger right) you would only need to declare the method once and xbase would know that the method's parameters may be swapped implicitly. I have to correct myself about the first example, since addition on string an int is not commutative, since ("x" + 1) != (1 + "x") because "x1" != "1x".
Ok, I understand but I don't think it's worth a language-level feature.
It was more an idea, I'm not insisting on this. I'm closing this. If somebody thinks this is an important feature, please reopen.