在 groovy 中一次性进行 Null 和空检查

问题描述 投票:0回答:3

有人可以澄清以下问题吗?

下面的验证在 myVar 中传递 null 时抛出 NULL 指针错误。正是因为

!myVar.isEmpty()

if (myVar!= null || !myVar.isEmpty() ) {
             
             some code///
                }

以下工作按预期进行,

if (myVar!= null) {
        if (!myVar.isEmpty()) {
             some code///

                }

将这两个步骤结合在一起的任何其他方式。

groovy
3个回答
13
投票

如果

.isEmpty()
用于字符串,那么您也可以只使用 Groovy 直接“truth”,因为
null
以及空字符串都是“false”。

[null, "", "ok"].each{
    if (it) {
        println it
    }
}
// -> ok

5
投票
if ( myVar!= null && !myVar.isEmpty() ) {
    //some code
}

相同
if ( !( myVar== null || myVar.isEmpty() ) ) {
    //some code
}

并使其更短 - 最好添加像

hasValues

这样的方法

然后检查可能是这样的:

if( myVar?.hasValues() ){
    //code
}

最后让它变得更棒 - 创建一个方法

boolean asBoolean()

class MyClass{
    String s=""
    boolean isEmpty(){
        return s==null || s.length()==0
    }
    boolean asBoolean(){
        return !isEmpty()
    }
}

def myVar = new MyClass(s:"abc")

//in this case your check could be veeery short
//the following means myVar!=null && myVar.asBoolean()==true
if(myVar) {
    //code
}

0
投票

除了显示更好的方法来检查变量内容的特定于常规的答案之外,您使用的布尔运算符是不正确的。两个术语之间必须存在逻辑与:

myVar != null && !myVar.isEmpty()

在这种情况下,如果 myVar 实际上 is null (=false),则不再计算表达式的第二部分,因为完整的表达式无法再变为 true。另一方面,逻辑 OR 会强制计算 term 的第二部分,并在 myVar 为 null 时失败。

基于语言的“如果这个为真,我不想这样做”和逻辑“或”之间存在差异。

© www.soinside.com 2019 - 2024. All rights reserved.