Odinodin
Odinodin

Reputation: 2177

Groovy range iteration without parenthesis

The following Groovy code prints a range of numbers from 1 to 5.

(1..5).each {println it}

However, when I forget to add the parenthesis, and do this:

1..5.each { println it}

It prints only 5

Why is this legal Groovy syntax? I would expect this to either behave as the (1..5) version or to throw an exception saying that I have forgotten the parenthesis.

Upvotes: 4

Views: 132

Answers (2)

cfrick
cfrick

Reputation: 37043

The .-Operator has a higher precedence in groovy than .. Source:

Operator Overloading

The precedence heirarchy of the operators, some of which we haven't looked at yet, is, from highest to lowest: $(scope escape)

  new ()(parentheses)
  [](subscripting) ()(method call) {}(closable block) [](list/map)
  . ?. *. (dots)
  ~ ! $ ()(cast type)
  **(power)
  ++(pre/post) --(pre/post) +(unary) -(unary)
  * / %
  +(binary) -(binary)
  << >> >>> .. ..<
  < <= > >= instanceof in as
  == != <=>
  &
  ^
  |
  &&
  ||
  ?:
  = **= *= /= %= += -= <<= >>= >>>= &= ^= |=

Upvotes: 4

Will
Will

Reputation: 14539

5.each has priority over 1..5 in the Groovy parser. It works because it is doing something like this:

ret = 5.each { println it }
range = 1..ret
assert range == [1, 2, 3, 4, 5]

The return of each is the collection itself

Upvotes: 4

Related Questions