Groovy – Operator overloading

Yeah. this is one of the things that promotes a language from “ah ! I use it”  into “ah ! Look what I can do!” Among other cool things to groovy up your work, operator overloading is an absolute must know if you plan to fascinate yourself (and of course your PM) . Cutting to the chase here is the sample code

class Money{
    int amount;
    String currency;
    Money plus(Money m){
        return new Money(amount:(m.amount+amount),currency:currency)
    }
}
Money m= (new Money(amount:1)+new Money(amount:2))
println m.amount

 

Ok. unfortunately groovy doesn’t support specifying operator character in method signature and this stems from the limitation from java [ groovy has its roots at the jvm ]. The example above may not provoke more than mere “thats cool” but implications of this can be seen in GDK (groovy dev kit) with includes some extensions for java libraries. So when you say,

list=new ArrayList()
list<<1  // adds the element to the list

here the operator << corresponds to the leftShift method being overloaded in the arrayList . This is groovy’s style of saying   “ list.add(1) where List should have Integer generics” as you say in java. Yes you guessed right :  “autoboxing” is something groovy provides out of the box.

Not yet groovy? Combine the operator overloading with the use construct.

class FakeAdder{
    static Object plus(Integer a,Integer b){
        return a*b   //this is not a bug!!
    }
}
use(FakeAdder){
    println 2+5
}

Output: 10

The operator + has been overloaded in the specific context to multiply numbers rather that standard add. Very powerful indeed. Try it yourself and share your comments.

Leave a Reply