groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Paul King <>
Subject precedence rules for power operator vs -, +, ++, --
Date Sat, 06 Jun 2015 11:08:56 GMT

Hi everyone,

As part of documenting the existing behavior for Groovy in Action 2nd Edition, we noticed
an anomaly with precedence rules for the power operator. It is different compared to all the
other operators, e.g. "+", "*", etc., with respect to unary minus, unary plus, increment and
decrement. We are intending to fix this anomaly
in Groovy 2.5. This is documented as a breaking change in the normal way within the release
notes but thought it was worth also giving an additional heads-up email for any users of the
power operator so they can perform any remedial work well in advance of 2.5. No date yet has
been set for 2.5, but we hope to release a beta version in the not too distant future.

In a nutshell, if you have expressions like:

x ** y      // you aren't affected regardless of whether x and y are +ve or -ve
x ** -y     // you aren't affected; the anomaly is only on the left-hand expression
(-x) ** y   // you aren't affected; bracketing takes precedence
-3 ** 2     // if you want to keep the existing behavior, we recommend you bracket like this:
-(3 ** 2)

Before the change, the following executes:

def x = 5
assert -x ** 2 == -25  // treated as -(x ** 2)
assert --x ** 2 == 24  // treated as --(x ** 2)

This behavior is different to the other operators and different to what the comments in the
grammar describe as the intended behavior but the order of two rules was presumably accidentally
reversed in the grammar.

After the change, the following executes:

def x = 5
assert -x ** 2 == 25   // treated as (-x) ** 2
assert --x ** 2 == 16  // treated as (--x) ** 2

At this stage, we aren't planning to write a migration tool but such a tool wouldn't be too
hard to write if anyone has a huge migration task ahead of them. We suspect that most people
have probably already put in brackets or used variables which might themselves be -ve, so
as not to have weird behavior but some occurrences in the current form might also no doubt

Further details:

Cheers, Paul.

This email has been checked for viruses by Avast antivirus software.

View raw message