Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating values to List in groovy

Tags:

groovy

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.

like image 369
user1455116 Avatar asked Sep 13 '25 20:09

user1455116


2 Answers

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]
like image 138
tim_yates Avatar answered Sep 17 '25 18:09

tim_yates


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]]
like image 29
Matt Avatar answered Sep 17 '25 19:09

Matt