Reputation: 2144
I have a List a = [1, 2]
in groovy. I'm passing this as a parameter to a method and doing an a.add(3)
. This is adding the element at the end. But someone else is accessing the same array elsewhere and i do not want them to see any changes i make to this array. I came to know that we can pass arrays only as references (correct me if i'm wrong).
However, in JavaScript we have something like arr = [1, 2]
and arr.concat(3)
- this returns an array [1, 2, 3]
but if we print arr
, it still prints [1, 2]
.
Please let me know if there is any way to achieve this in groovy.
Upvotes: 4
Views: 7368
Reputation: 742
You can add lists together to concatenate. I prefer this to '+'ing a single element since everything has consistent types (List -> List -> List), so it still works if the 'element' you want to add is itself a collection.
def a = [ 1, 2 ]
def b = a + [3]
assert a == [1, 2]
assert b == [1, 2, 3]
def c = a + [[3, 4]]
assert c == [1, 2, [3, 4]]
Upvotes: 5
Reputation: 171154
You can use plus for this, as it creates a new list:
def a = [ 1, 2 ]
def b = a + 3
assert a == [1, 2]
assert b == [1, 2, 3]
Upvotes: 5