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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With