Saturday, December 8, 2007

Groovy Meta-programming

class Money { 
    int amount  
    Money(amt) {
        amount = amt
    }
}

dollar = new Money(1);
bigBill = new Money(100);
// create 'plus' class method (effects all instances)
Money.metaClass.plus << {Money moreMoney -> 
    delegate.amount += moreMoney.amount  
    delegate
}

assert dollar.plus(bigBill).amount == 101
assert bigBill.plus(bigBill).amount == 200