Search

Dark theme | Light theme

December 23, 2009

Groovy Goodness: We Can Handle the Truth

In Groovy 1.7 we can coerse objects to a boolean. We only have to provide the method asBoolean() and return true or false. This means our object can be used in a conditional context without accessing any other methods or properties.

class User {
    String username
    boolean active

    boolean asBoolean() { 
        active
    }
}

assert new User(username: 'mrhaki', active: true)
assert !new User(username: 'mrhaki', active: false)

// We can also add the asBoolean method with metaClass.
String.metaClass.asBoolean = {
    delegate == /sure/
}
assert !'true'
assert 'sure'