Opal
Opal

Reputation: 84824

Groovy comparison chaining

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?

Upvotes: 1

Views: 419

Answers (2)

tim_yates
tim_yates

Reputation: 171124

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)

Upvotes: 1

blackdrag
blackdrag

Reputation: 6508

A workaround would be using AST transformations of course: http://docs.groovy-lang.org/docs/next/html/documentation/core-metaprogramming.html#developing-ast-xforms

Upvotes: 1

Related Questions