if(!x) 是否与 if(x!=null) 相同
Is if(!x) the same as if(x!=null)
我知道他的有点像 Is if(pointerVar) the same as if(pointerVar!=NULL)?,但我还是要问一下。
在Groovy中,我们有以下内容:
def x = someMethod()
if( !x ) {
// do good stuff
}
这只是一个标准的 null
检查,即 (x != null)
,对吗?
没有。 groovy 中的 if
调用基础 asBoolean()
方法。这被称为 Groovy truth。
空列表,空字符串,空映射,null,0
,都是假值:
if ([:]) {
assert false
}
if (null) {
assert false
}
if ("") {
assert false
}
if (0) {
assert false
}
assert null.asBoolean() == false
assert 1.asBoolean()
也可以自己写asBoolean
类。
我知道他的有点像 Is if(pointerVar) the same as if(pointerVar!=NULL)?,但我还是要问一下。
在Groovy中,我们有以下内容:
def x = someMethod()
if( !x ) {
// do good stuff
}
这只是一个标准的 null
检查,即 (x != null)
,对吗?
没有。 groovy 中的 if
调用基础 asBoolean()
方法。这被称为 Groovy truth。
空列表,空字符串,空映射,null,0
,都是假值:
if ([:]) {
assert false
}
if (null) {
assert false
}
if ("") {
assert false
}
if (0) {
assert false
}
assert null.asBoolean() == false
assert 1.asBoolean()
也可以自己写asBoolean
类。