Test only if variable is not null in if statement

groovy, if-statement

Solution

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.

Problem

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?

Original source