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() {
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