Groovy follow below rules while evaluating the
expressions.
Non-Zero numbers are
evaluated to true
HelloWorld.groovy
nonZeroNumber = 10 zeroNumber = 0 printInfo (nonZeroNumber) printInfo (zeroNumber) void printInfo(obj){ if(obj){ println "$obj evaluated to true" }else{ println "$obj evaluated to false" } }
Output
10 evaluated to true
0 evaluated to false
Non-null objects are evaluated
to true
HelloWorld.groovy
obj1 = null obj2 = "Hello" printInfo (obj1) printInfo (obj2) void printInfo(obj){ if(obj){ println "$obj evaluated to true" }else{ println "$obj evaluated to false" } }
Output
null evaluated to false
Hello evaluated to true
Non-empty Strings,
GStrings and CharSequences are coerced to true.
HelloWorld.groovy
emptyStr = "" nonEmptyStr = "Hello World" printInfo(emptyStr) printInfo(nonEmptyStr) void printInfo(data){ if(data){ println "$data is evaluated to true" }else{ println "$data is evaluated to false" } }
Output
is evaluated to false
Hello World is evaluated to true
Non-empty Collections
and arrays are evaluated to true.
HelloWorld.groovy
emptyArray = [] emptyMap = [:] array = [1, 2, 3] map = ['color':'Blue', 'shape':'Circle'] printInfo(emptyArray) printInfo(emptyMap) printInfo(array) printInfo(map) void printInfo(data){ if(data){ println "$data is evaluated to true" }else{ println "$data is evaluated to false" } }
Output
[] is evaluated to false
[:] is evaluated to false
[1, 2, 3] is evaluated to true
[color:Blue, shape:Circle] is evaluated to true
Evaluate to true, if
the matcher has atleast one match
HelloWorld.groovy
def text = "aaaab" if (text =~ /a*b/){ println 'Evaluate to true' }else{ println "Evaluated to false" }
Output
Evaluate to true
Iterators and
Enumerators with further elements are evaluated as true
HelloWorld.groovy
Iterator iter1 = [0].iterator() Iterator iter2 = [].iterator() Vector vector1 = [0] as Vector Enumeration enumerator1 = vector1.elements() Vector vector2 = [] as Vector Enumeration enumerator2 = vector2.elements() printInfo(iter1, "iter1") printInfo(iter2, "iter2") printInfo(enumerator1, "enumerator1") printInfo(enumerator2, "enumerator2") void printInfo(obj, message){ if(obj){ println "$message evaluated to true" }else{ println "$message evaluated to false" } }
Output
iter1 evaluated to true
iter2 evaluated to false
enumerator1 evaluated to true
enumerator2 evaluated to false
No comments:
Post a Comment