Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Groovy, can you use Range as a List?

Tags:

groovy

According to the Groovy docs:

Ranges allow you to create a list of sequential values. These can be used as Lists since Range extends java.util.List.

However, in my case I need the List to end up as a String, including the square brackets. I tried the following:

def myRange = 1..5
def myList = [1, 2, 3, 4, 5]
// this passes
assert myRange == myList
// both of the following fail!
assert myRange.toString() == myList.toString()
assert myRange.subList(0, 5).toString() == myList.toString()

Am I missing something?

like image 884
SiKing Avatar asked Oct 21 '25 09:10

SiKing


1 Answers

Extending something does not mean that its toString will be the same.

If you have to get the same output as with a list, try

myRange.toList().toString()

Or

"[${myRange.join(',')}]"

Or (adding comment as an easy answer for you)

assert (1..5).toListString() == "[1, 2, 3, 4, 5]"
like image 175
tim_yates Avatar answered Oct 25 '25 00:10

tim_yates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!