开发者

How do I modify an existing Java class to overload an operator in Groovy?

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 c开发者_运维技巧oding. 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜