Reputation: 999
I wrote this part of code.
Integer value = 0
if(value) {
print "true"
} else {
print "false"
}
And the output of code is false
.
Can someone explain me why does Integer 0 value behaves as false in this if statement when it is not null and it exists?
Upvotes: 3
Views: 5532
Reputation: 42194
When Groovy sees a variable in the context where a boolean value is expected, it invokes DefaultGroovyMethods.asBoolean(object)
method to coerce given value to its boolean representation. For numbers following code gets executed:
/**
* Coerce a number to a boolean value.
* A number is coerced to false if its double value is equal to 0, and to true otherwise,
* and to true otherwise.
*
* @param number the number
* @return the boolean value
* @since 1.7.0
*/
public static boolean asBoolean(Number number) {
return number.doubleValue() != 0;
}
Source: src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
That is why Groovy coerce 0 to false
and any non-zero number to true
.
There are other coercions that Groovy mades for you, e.g. empty list coerces to false
, empty string coerces to false
etc. I have written an article about some of them, you might find it useful.
Upvotes: 9
Reputation: 37033
It's part of the "Groovy Truth"
5.7. Numbers
Non-zero numbers are true.
assert 1 assert 3.5 assert !0
Upvotes: 5