Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 71 ]

if(condition) {
} else if (condition) {
} else {
}

Groovy Truth

The only difference is in how Groovy interprets the if conditions. Groovy can
promote a number of non-Boolean conditions to true or false. So, for instance,
a non-zero number is always true. This wider, more all-encompassing notion of
what can be true is often referred to as "Groovy Truth":


// Java non zero test
int n = 1;
if ( n != 0) {
}
// Groovy equivalent does not need to form a boolean expression
def n = 1;
if (n) {
}

Other "Groovy Truths" are as shown in the following code. In other words,
when taken in the context of a predicate, these values will all equate to a
Boolean true value:


given: "An initialized value"
String initialized = "Some Value"
Customer customer = new Customer(name: "Joey")
def array = [1,2,3]
def map = [a:1,b:2]
expect: "it will evaluate to true"
initialized
customer
array
map

Now, let's look at some "Groovy Falsehoods". Things which when used as a
predicate will equate to a Boolean false value are:


given: "A null uninitialized or empty value"
String nullString = null
String uninitializedString
Customer customer = null
def array = []
def map = [:]
def emptyString = ''
Free download pdf