仅在if语句中变量不为null时进行测试

Mat*_*own 15 groovy if-statement

我有以下方法,我只想在传入的情况下测试该event.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}")
}
Run Code Online (Sandbox Code Playgroud)

我认为可以这样做,但它似乎不起作用:

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}")
}
Run Code Online (Sandbox Code Playgroud)

有什么办法可以做到吗?或者我必须回到这样的事情:

if (status != null) {
    return events.find {
        it.description == desc && it.status == status
    }
} else if (status == null) {
    return events.find {
        it.description == desc
    }
}
Run Code Online (Sandbox Code Playgroud)

有某种最佳做法吗?

Dav*_*ton 22

我不相信这个表达是合情合理的.

埃尔维斯的意思是"如果真的,使用价值,否则使用其他东西."

你的"其他东西"是一个闭包,价值是status != null,它们似乎都不是你想要的.如果status null,Elvis说true.如果不是,你会得到一层额外的封闭.

为什么你不能使用:

(it.description == desc) && ((status == null) || (it.status == status))
Run Code Online (Sandbox Code Playgroud)

即使是没有工作的,你需要的是关闭返回适当的值,对不对?没有必要创建两个单独的find调用,只需使用一个中间变量.