carlTEJ
carlTEJ

Reputation: 45

Map syntax in groovy?

I stumbled across this syntax in a groovy script :

a[x,y]

What does it mean ?

Upvotes: 3

Views: 248

Answers (1)

jalopaba
jalopaba

Reputation: 8129

It is a way of slicing with the subscript operator:

The subscript operator is a short hand notation for getAt or putAt, depending on whether you find it on the left hand side or the right hand side of an assignment

You can use it on lists, arrays, maps and also strings:

def a = 'hello'
assert a[0,1] == 'he'
assert a[0..1] == 'he'
assert a[0..2] == 'hel'
assert a[0,2] == 'hl'
assert a[0,2,4] == 'hlo'
assert a[0..-1] == 'hello'
assert a[0..-2] == 'hell'

An example with getAt and putAt:

def list = [1, 0, 3, 0, 5]
list[1,3] = [2,4]
assert list == [1, 2, 3, 4, 5]

Upvotes: 5

Related Questions