Apolymoxic Apolymoxic - 1 year ago 160
Groovy Question

Groovy Elvis operator with and logic

This may be a silly question, but I am curious how this operates -

If I have an Elvis operator with an and / or logic in the then clause, how should I write the operation? That sounds confusing, I know, so let me give an example...

testVal = test1 ?: test2 && test3

Is EVERYTHING on the right side of the Elvis operator considered a separate entity, or is it only what is immediately to the right?

Meaning, does groovy read the code as

testVal = (test1 ?: test2) && test 3

If test1 fails, do test2 - let's call this result test12.
testVal = test12 && test3

or does it read it as

test1 ?: (test2 && test3)

If test1 fails, do test2 and test 3 - let's call this result test23.
testVal = test1 && test23

Answer Source

Please have a look on operator precedence section in Groovy documentation.

Operator && has lower precedence than ?: so the option test1 ?: (test2 && test3) will be correct.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download