Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between 1..5, [*1..5] and [1..5] in Groovy?

Tags:

range

groovy

In Groovy,what is the difference between,

def a=1..5
def b= [*1..5]
def c=[1..5]

what does * in [*1..5] symbolize?

like image 223
user2697202 Avatar asked Aug 19 '13 17:08

user2697202


1 Answers

* represents a Spread Operator. Elaborating your example:

a = 1..5
b = [*1..5]
c = [1..5]

assert a.class.name == "groovy.lang.IntRange" //Is a range from 1 till 5
assert b.class.name == "java.util.ArrayList" //Spread the range in a list
assert c.class.name == "java.util.ArrayList" //Is a list

Extending @ataylor's explanation:

assert a.size() == 5
assert b.size() == 5
assert c.size() == 1

To reach each element in c you have to iterate over it (which is a range)

c.each{println it}

Groovy Goodness by Mr Haki has a detailed example of its usage.

like image 168
dmahapatro Avatar answered Nov 30 '22 07:11

dmahapatro