4

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.

1
  • 1
    .each probably binds stronger than .., so your second command is equivalent to 1..(5.each { println it}) where the range is unused. Commented Sep 29, 2014 at 13:01

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

4

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 == != <=> & ^ | && || ?: = **= *= /= %= += -= <<= >>= >>>= &= ^= |= 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.