Alex
Alex

Reputation: 23

Range operator in Groovy not printing entire range of numbers

New to groovy and following tutorial on Tutorialspoint and got stuck on range operators here

Under range operators, notation provided is def range = 0..5

The code snipped they used to show an example

class Example {
  static void main(String[] args) {
    def range = 5..10;
    println(range);
    println(range.get(2));
  }
}

Output should be

[5, 6, 7, 8, 9, 10]
7

Executing that same snipped I am getting

5..10
7

I tried that example and removing semicolons but get the same result. Could you explain what am I doing wrong here, thank you.

Upvotes: 2

Views: 1055

Answers (2)

doelleri
doelleri

Reputation: 19682

What you're doing is printing the IntRange object you're creating with 5..10. You can see that IntRange's toString() will print exactly what you're getting.

To print each of the items in the range, you'd need to use a loop.

range.each {
    println it
}

However, that won't give you the exact output you're looking for as each number will be on its own line.

Upvotes: 2

tim_yates
tim_yates

Reputation: 171144

You're expecting a list in your first print

If you have to, you can do

println range.toList()

Upvotes: 5

Related Questions