groovy 中的 null 和空签入

SMP*_*MPH 2 groovy

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

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

if (myVar!= null || !myVar.isEmpty() ) {
             
             some code///
                }
Run Code Online (Sandbox Code Playgroud)

下面的工作虽然符合预期,

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

                }
Run Code Online (Sandbox Code Playgroud)

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

cfr*_*ick 10

如果.isEmpty()在字符串上使用,那么您也可以直接使用 Groovy“truth”,因为null空字符串也是“false”。

[null, "", "ok"].each{
    if (it) {
        println it
    }
}
// -> ok
Run Code Online (Sandbox Code Playgroud)