I stumbled across this syntax in a groovy script :
a[x,y]
What does it mean ?
It is a way of slicing with the subscript operator:
The subscript operator is a short hand notation for
getAtorputAt, 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With