Tutorial by Examples

for numbers, a zero value evaluates to false, non zero to true int i = 0 ... if (i) print "some ${i}" else print "nothing" will print "nothing"
a string (including GStrings) evaluates to true if not null and not empty, false if null or empty def s = '' ... if (s) println 's is not empty' else println 's is empty' will print: 's is empty'
Collections and Maps evaluates to true if not null and not empty and false if null or empty /* an empty map example*/ def userInfo = [:] if (!userInfo) userInfo << ['user': 'Groot', 'species' : 'unknown' ] will add user: 'Groot' , species : 'unknown' as default userInfo since the u...
a null object reference evaluates to false, a non null reference to true, but for for strings, collections, iterators and enumerations it also takes into account the size. def m = null if (!m) println "empty" else println "${m}" will print "empty" de...
Sometimes it may be useful to have a specific asBoolean definition in your own program for some kind of objects. /** an oversimplified robot controller */ class RunController { def complexCondition int position = 0 def asBoolean() { return complexCondition(this...
a Character evaluates to true if it's value is not zero, false if zero assert ! new Character((char)0) assert ! new Character('\u0000Hello Zero Char'.charAt(0)) assert new Character('Hello'.charAt(0))
a Matcher evaluates to true if it can find at least one match, false if no match is found // a match is found => true assert 'foo' =~ /[a-z]/ // the regexp does not match fully => no match => false assert !( 'foo' ==~ /[a-z]/ ) // a match is found => true assert 'foo' =~ /o/ // no...
The evaluation of a closure is the evaluation of the result of the closure. All rules applies : if the closure returns a null , zero number or empty String, Collection, Map or Array it evaluates to false otherwise to true. // Closure return non zero number => true assert { 42 }() // closure ...

Page 1 of 1