Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 72 ]

expect: "it will evaluate to false"
!nullString
!uninitializedString
!customer
!array
!map
!emptyString

As with many Groovy language features, Groovy's loose interpretation of what can
be true allows for much more succinct and understandable branching conditions.
From Groovy 1.7, Groovy Truth got even more useful. Now, any class can implement
the asBoolean method to define what it means for it to be true:


enum Status {
ACTIVE,
INACTIVE,
DELETED
def asBoolean () {
this == Status.ACTIVE
}
}

In this example, we will implement a Status enum where only ACTIVE is considered
to be true:


expect: "Only Status.ACTIVE will return true from asBoolean"
Status.ACTIVE
!Status.INACTIVE
!Status.DELETED

Ternary and Elvis operators

The standard Java ternary operator (a? b : c) is supported. Groovy also has
another similar operator, the bizarrely named Elvis operator (a? : b). We can
express the ternary operation as a traditional if-else branch as follows:


// Ternary operator
x > 0? y = 1 : y = 2

// Is same as
if (x > 0)
y = 1
else
y = 2

http://www.ebook3000.com
Free download pdf