Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

Boolean expressions

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

Code Block
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.

Code Block
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

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

Code Block
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.

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

Matchers

Matching regex patterns are coerced to true.

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

Strings

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

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

Numbers

Non-zero numbers are coerced to true.

Code Block
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.

Code Block
assert new Object()
assert !null