If statement 为什么0整数值在groovy的if语句中表现为false?
我写了这部分代码If statement 为什么0整数值在groovy的if语句中表现为false?,if-statement,groovy,If Statement,Groovy,我写了这部分代码 Integer value = 0 if(value) { print "true" } else { print "false" } 代码的输出为false。 有人能解释一下为什么整型0值在这个if语句中不为null且存在时会表现为false吗?它是“”的一部分 5.7。数字 非零数字是真的 assert 1 assert 3.5 assert !0 当Groovy在期望布尔值的上下文中看到变量时,它调用DefaultGroovyMethods.asBoo
Integer value = 0
if(value)
{
print "true"
}
else
{
print "false"
}
代码的输出为false
。
有人能解释一下为什么整型0值在这个if语句中不为null且存在时会表现为false吗?它是“”的一部分
5.7。数字
非零数字是真的
assert 1
assert 3.5
assert !0
当Groovy在期望布尔值的上下文中看到变量时,它调用
DefaultGroovyMethods.asBoolean(object)
方法将给定值强制为其布尔表示。对于数字,执行以下代码:
/**
* 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;
}
资料来源:
这就是为什么Groovy将0强制为false
,将任何非零数字强制为true
Groovy还为您提供了其他强制,例如空列表强制为false
,空字符串强制为false
等等。我已经编写了一个示例,您可能会发现它很有用