Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map syntax in groovy?

Tags:

groovy

I stumbled across this syntax in a groovy script :

a[x,y]

What does it mean ?

like image 477
carlTEJ Avatar asked Jul 21 '26 18:07

carlTEJ


1 Answers

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]
like image 96
jalopaba Avatar answered Jul 28 '26 01:07

jalopaba



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!