Skip to: Site menu | Main content

Groovy 

      Download | Documentation | Developers | Community

An agile dynamic language for the Java Platform

Groovy Truth Add comment to Wiki View in Wiki Edit Wiki page Printable Version

Boolean expressions

Groovy supports the standard conditional operators on boolean expressions, e.g.:

def a = true
def b = true
def c = false
assert a
assert a && b
assert a || c
assert !c

In addition, Groovy has special rules for coercing non-boolean objects to a boolean value.

Collections

Empty collections are coerced to false.

def numbers = [1,2,3]
assert numbers //true, as numbers in not empty
numbers = []
assert !numbers //false, as numbers is now an empty collection

Iterators and Enumerations

Iterators and Enumerations with no further elements are coerced to false.

assert ![].iterator() // false because the Iterator is empty
assert [0].iterator() // true because the Iterator has a next element
def v = new Vector()
assert !v.elements()  // false because the Enumeration is empty
v.add(new Object())
assert v.elements()   // true because the Enumeration has more elements

Maps

Non-empty maps are coerced to true.

assert ['one':1]
assert ![:]

Matchers

Matching regex patterns are coerced to true.

assert ('Hello World' =~ /World/) //true because matcher has at least one match

Strings

Non-empty Strings, GStrings and CharSequences are coerced to true.

// Strings
assert 'This is true'
assert !''
//GStrings
def s = ''
assert !("$s")
s = 'x'
assert ("$s")

Numbers

Non-zero numbers are coerced to true.

assert !0 //yeah, 0s are false, like in Perl
assert 1  //this is also true for all other number types

Object references

Non-null object references are coerced to true.

assert new Object()
assert !null