天天看點

groovy if 判斷字元串_groovy – 僅在if語句中的變量不為null時才測試

我有以下方法,我隻想測試event.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

}

}

有沒有一些最佳做法?