Groovy 仅当if语句中的变量不为null时测试

Groovy 仅当if语句中的变量不为null时测试,groovy,if-statement,Groovy,If Statement,我有以下方法,仅当传入了status时,我才想测试事件.status属性: def findEvent(String desc, String status = null, Collection events) { return events.find { it.description == desc && \\If status is not null: it.status == status } thr

我有以下方法,仅当传入了
status
时,我才想测试
事件.status
属性:

def findEvent(String desc, String status = null, Collection events) {
        return events.find {
            it.description == desc && \\If status is not null: it.status == status
        }

        throw new Exception("Review Event Record Not Found: ${desc}")
}
我以为可以这样做,但似乎不起作用:

def findEvent(String desc, String status = null, Collection events) {
        return events.find {
            it.description == desc && (status != null ?: {it.status == status})
        }

        throw new Exception("Review Event Record Not Found: ${desc}")
}
有没有办法做到这一点?还是我必须回到这样的话题:

if (status != null) {
    return events.find {
        it.description == desc && it.status == status
    }
} else if (status == null) {
    return events.find {
        it.description == desc
    }
}

有什么最佳实践吗?

我不相信这个表达方式是如此的感性

猫王的意思是“如果是真的,使用价值,否则使用其他东西。”

您的“其他东西”是一个闭包,其值为
status!=null
,两者似乎都不是您想要的。如果
状态
为空,埃尔维斯说
为真
。如果不是,你会得到一个额外的封闭层

为什么你不能直接使用:

(it.description == desc) && ((status == null) || (it.status == status))
即使这不起作用,您所需要的只是闭包来返回适当的值,对吗?无需创建两个单独的
find
调用,只需使用一个中间变量。

(it.description==desc)和((status==null)| |(it.status==status))看起来很完美。我会在有机会的时候确认它有效。无可否认,这是我第一次遇到猫王接线员,所以我有点像在黑暗中玩。干杯,戴夫