It was a design decision in the early days of Groovy for the assignment operators, like "+=", not to be first class operators in their own right but to always map onto an assignment and the underlying operator. Since the mapping happens late in the compilation process, you could write an AST transform and provide your own hook to such binary expressions to emulate them being first class operators, but most folks use another operator in such scenarios, e.g.:
myMatrix << additionalRows Another option is to have immutable/mutable wrappers, e.g.: myMatrix.mutable += additionalRows While Groovy gives you great flexibility, it is often best to not try to be too fancy with different operators having different immutable/mutable semantics. Cheers, Paul. <https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail> Virus-free.www.avast.com <https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail> <#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2> On Mon, Oct 28, 2024 at 4:02 AM Per Nyfelt <p...@alipsa.se> wrote: > > Hi, > > Is it possible to override plus equals (+=) for a class? > > I have a class the is want plus to be immutable and plusEquals to be > mutable e.g: > > def newMatrix = myMatrix + additionalRows > > assert myObj == myMatrix - additionalRows > > myMatrix += additionalRows > > assert myMatrix == newMatrix > > Since my implementation of plus involves cloning myMatrix which in my > case is expensive, it would be a big difference if I could avoid that > when there is no need. However += is calling plus and then assigning > the result under the covers. Is there a way to "get to it" to override? > > Best regards, > > Per >