60

I think I've got some funny expectations... I want to iterate the numbers from 1 to 10. As a while loop it goes like this:

def countMe = 1 while (countMe<11) { println countMe countMe++ } 

I was expecting that the following would do this also:

[1..10].each { println it } 

But it actually prints the IntRange, not each Integer in the range. What is the (syntactically) closest way to my [x..y].each{} fantasy to get each of a list of numbers?

1 Answer 1

114

Use parentheses not brackets:

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

[1..10] is a list of length 1 containing a single range.

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

1 Comment

You need to remember [1..10] only means a range when it's a subscript AFTER another variable. When it stands alone, then it's a LIST OF a range. These little inconsistencies arise because Groovy tries hard to extend Java's syntax with its own additions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.