Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy range iteration without parenthesis

Tags:

groovy

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.

like image 920
Odinodin Avatar asked Feb 12 '23 22:02

Odinodin


1 Answers

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

like image 102
Will Avatar answered Feb 14 '23 12:02

Will