Wednesday, December 2, 2009

Groovy Goodness: Automatic Return Value Casting

If Groovy knows the return type of a method it will automatically cast our return value to that type. We don't have to explicitly cast our value.

String simple() {
    42
}
assert 'java.lang.String' == simple().class.name 
assert '42' == simple()

class User {
    String name, email
}

User createUser() { 
    [name: 'mrhaki', email: 'mail@host.com']
}
assert createUser() instanceof User
assert 'mrhaki' == createUser().name
assert 'mail@host.com' == createUser().email

2 comments:

Mike Miller said...

Mr. Haki,

minor typo - change the last line to createUser().email from createuser().email - it can't find the createuser method (uppercase U)

mrhaki said...

@Mike Miller: thanks for finding the typo, I've changed the sample code.