Loading...

March 11, 2010

Groovy Goodness: Use Keywords as Method Names

Normally we cannot use keywords in Java or Groovy to use as method names. But in Groovy we can. We need to enclose the keyword between single or double quotes as we define the method. In the following example we create a method with the name switch, which is a Java/Groovy keyword.

class User {

    String username
    
    String 'switch'() {
        username = username.reverse()
    }

}

def u = new User(username: 'mrhaki')
assert 'ikahrm' == u.switch()