views:

34

answers:

1

I'm implementing a few math classes and for the first time finding problems with Java (cumbersome and duplicated code) that I really can't overcome by cleaver coding. Operator overloading would be REALLY handy, and there are a few other things that Groovy can do a lot better (I may also try Scala at some point).

So I'm still writing the primary classes (Right now Complex and Matrix) in Java, but I'm going to use them from Groovy.

I changed the names of some methods (.add) to take advantage of operator overloading (.plus).

Now, my classes interact very well with the "Number" base class, so I can use:

complex.add(number); //or 
complex = complex + number;

and get an awesome answer, but I cannot use:

complex = number + complex

since number doesn't understand .add(Number) and even if it did, it wouldn't know how to handle the Number if it turned out to be a complex.

Can I write a number.plus(complex) and add it to the number interface? The code would actually be pretty easy, I could just reverse it:

Number plus(complex) {
     return complex.plus(this);
}

This would work for everything of type number, but I don't know if Groovy can graft this to the number interface after the fact. (Also, Number and Complex are in Java, so I kind of see this as an add-in for groovy).

Any other advice? Should I just give in and learn Scala?

Oh, I realize that there are probably packages out there that can do this already, but part of it is just learning the math, I'm working through a quantum computing text and am implementing the exercises as I go.

+1  A: 

You can add the required methods as closures to the Number metaclass.

For example (taking advantage of commutativity of addition):

Number.metaClass.plus << { Complex complex ->
    complex.plus(delegate)
}

After this, any Number subclass can be on the left-hand side of the equation too. Make sure you use the append operator << to avoid clobbering other overloaded plus metamethods. Number is referenced as delegate instead of this since it's a closure.

ataylor
That works, awesome. I'll have to take some time to get to understand it--but it gives me a good idea where to start.
Bill K