Dark theme | Light theme

December 22, 2009

Groovy Goodness: Implementing MetaClass Methods with Same Name but Different Arguments

Using the metaClass property of a class we can add new methods or override existing methods of the class. If we want to add a new methods that have the same name, but different arguments, we can use a shortcut notation. Groovy allows us to chain multiple leftShift() (<<) methods together.

String.metaClass.groovy << { Integer number ->
    delegate * number
} << { String s ->
    delegate + s
} << { ->
    delegate + ' Groovy rocks.'

assert 'GroovyGroovy' == 'Groovy'.groovy(2)
assert 'Hello world from Groovy' == 'Hello world'.groovy(' from Groovy')
assert 'It is true. Groovy rocks.' == 'It is true.'.groovy()