Search

Dark theme | Light theme

December 20, 2009

Groovy Goodness: Adding or Overriding Methods with ExpandoMetaClass

In Groovy we can add new methods to classes with ExpandoMetaClass using the leftShift (<<) operator. If the method already exists we get an error. To override an existing method we can use the equal operator (=). But we can also use the equal operator (=) to add a new method, but then we don't get an error when the method already exists.

Integer.metaClass.eights << { delegate * 8 }
assert 32 == 4.eights()

Integer.metaClass.hundreds = { delegate * 100 }
assert 200 == 2.hundreds()

try {
    Integer.metaClass.toString << { 'Groovy' } // Cannot use << for existing method.
    assert false
} catch (e) {
    assert 'Cannot add new method [toString] for arguments [[]]. It already exists!' == e.message
}

Integer.metaClass.toString = { 'Groovy' }
assert 'Groovy' == 100.toString()