Groovy iteration without parentheses

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 only prints 5

Why is this legal Groovy syntax? I would expect this to behave like version (1..5), or throw an exception, saying I forgot the parentheses.

+3


source to share


2 answers


5.each

takes precedence over 1..5

the groovy parser. It works because it does something like this:

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

      



The return each

is the collection itself

+3


source


.

-Operator has higher precedence in groovy than ..

Source :



Operator overloading

The original hierarchy of operators, some of which we haven't covered yet, from highest to lowest: $ (area release)

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

      

+3


source







All Articles