I have the following method where I want to test the event.status
property only if status
has been passed in:
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}")
}
I thought it could be done like this, but it doesn't seem to work:
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}")
}
Is there any way this could be done? Or do I have to go back to something like this:
if (status != null) {
return events.find {
it.description == desc && it.status == status
}
} else if (status == null) {
return events.find {
it.description == desc
}
}
Is there some kind of best practice?
The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With