In Groovy, can you use Range as a List?

groovy

Solution

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]"

Problem

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?

Original source