Mittwoch, 22. Oktober 2014

Xtend - Operator Overloading

Xtend has a nice list of operators you can use out of the box. But you can also overload them for your own types and even for types that others have written. Let's just look at a typical numeric type, Complex numbers:

As you can see, overloading an operator is just done by writing a method whose name matches the operator and its signature. In our example I have overloaded the binary plus and minus operators as well as the unary minus operator. I left out the constructor, toString, equals, hashCode etc. In an upcoming post you will see that Xtend can automatically generate all of these for you.

Now let's see our new number type in action:

The operators work just like you would expect, but the last line is something especially cool: By defining +, you get += for free! But all those constructor calls don't look like we are used to in mathematics. We want to write 1 + 2i. To do this, we add the following static methods to our Complex class

These methods actually extend the double type so it can also be added to and multiplied with Complex numbers. You can add operators to any existing type like this! Now we just need to import them as static extensions in our example and we get a much cleaner syntax.

There's one final tip I want to give you about the compound (+=, -=, *=, /=) operators. In the case of mutable types it makes sense to overload them with a different meaning than +, -, *, /

For example, the Xtend library defines the +-operator for List to mean "create a concatenated view of both Lists, without changing them".

The +=-operator on the other hand means "add all elements of the second list to the first one", which is more efficient if mutating the first list is okay.