Loading...

Thursday, 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()

5 comments:

Condolence Sms said...

Its really very nice and informative post. thanks for sharing us.

Jeff said...

Well... we CAN do it.

The only context where this is not complete misanthropy on par with naming your variables a, b and c is if you're making some domain specific language where it won't be obvious to the user of that language that they're using Groovy.

Andrew Eisenberg said...

Interesting...and it is even possible to use the same technique to use non-ASCII characters in your method names.

However, I would be very, very cautious to try using keywords as variables. Even in the case that Jeff mentions, I'd use a synonym.

Giridhar Pottepalem said...

It is nice to know that it is possible in Groovy.

suzain said...

Haki ! you are too good yaar.
Sample messages

Post a Comment