Jak*_*sić 1 groovy if-statement
我写了这部分代码.
Integer value = 0
if(value)
{
print "true"
}
else
{
print "false"
}
Run Code Online (Sandbox Code Playgroud)
而代码的输出是false.有人可以解释一下,为什么Integer 0值在这个if语句中表现为false,当它不为null并且它存在时?
当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;
}
Run Code Online (Sandbox Code Playgroud)
来源:src / main / org / codehaus / groovy / runtime / DefaultGroovyMethods.java
这就是为什么Groovy强制0到false和任何非零数字到的原因true。
Groovy还为您提供了其他强制性,例如,空列表强制性false,空字符串强制性false等。我写了一篇有关其中的文章,您可能会发现它很有用。
这是" Groovy Truth " 的一部分
5.7.数字
非零数字是真的.
Run Code Online (Sandbox Code Playgroud)assert 1 assert 3.5 assert !0
| 归档时间: |
|
| 查看次数: |
749 次 |
| 最近记录: |