Groovy comparison chaining

399 views Asked by At

In python the following statement returns correct results:

>>> 1 == 1 == 1
True
>>> 1 == 1 == 0
False

Is such construct (or similar) possible in groovy? The following fails:

groovy:000> 1 == 1 == 1
===> false

since the first comparison is evaluated to true and true is not equal to 1. Any workaround on this?

2

There are 2 answers

3
blackdrag On
0
tim_yates On

Or if not the AST route you're stuck with:

(1 == 1) && (1 == 1)

Which you could do programatically with something like:

public <T> Boolean allEqual(T... elements) {
    elements.toList().collate(2, 1, false).every { a, b -> a == b }
}

assert allEqual(1, 1, 1)