groovyGroovy Truth (true-ness)


Remarks

Groovy evaluates conditions in if, while and for statements the same way as Java does for standard Java conditions : in Java you must provide a boolean expression (an expression that evaluates to a boolean) and the result is the result of the evaluation.

In Groovy , the result is the same as in Java for thoses conditions (no examples provided, this is standard Java).

The other truthfulness evaluation mechanism shown by examples can be summarized as:

  • numbers: a zero value evaluates to false, non zero to true.
  • objects: a null object reference evaluates to false, a non null reference to true.
  • Character : a character with a zero value evaluates to false, true otherwise.
  • String : a string evaluates to true if not null and not empty, false if null or empty (applies to GStrings and CharSequences too).
  • Collections and Maps (including subclasses List, Map, Set, HashSet ...) : also takes into account the size, evaluates to true if the collection is not null and not empty, false if null or empty.
  • Enumerations and Iterators evaluates to true if not null and they are some more elements (groovy evaluates hasMoreElements or hasNext on the object), false if null or no more elements.
  • Matcher : a matcher evaluates to true if there is at least one match, false if not match is found.
  • Closure : a closure evaluates to the evaluation of the result returned by the closure.

The asBoolean method can be overriden in a user defined class to provide custom boolean evaluation.