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.
Empty collections are coerced to false.
def numbers = [1,2,3] assert numbers //true, as numbers in not empty numbers = [] assert !numbers //true, as numbers is now an empty collection |
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 |
Non-empty maps are coerced to true.
assert ['one':1] assert ![:] |
Matching regex patterns are coerced to true.
assert ('Hello World' =~ /World/) //true because matcher has at least one match
|
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")
|
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 |
Non-null object references are coerced to true.
assert new Object() assert !null |