saurav
saurav

Reputation: 422

Adding elements to a list in Groovy

Suppose I have a list in groovy code as:

l = [1,2,3,4]

Now when I use the below code, it changes the list:

println(l<<5)

Now our list is [1,2,3,4,5]

But when I am using this code:

println(l+[6])

Nothing happens to the list (except it prints with a 6 at the end.) But the list is same as [1,2,3,4,5]

What's going on in here? Help please. Thanks

Upvotes: 0

Views: 1105

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27255

println(l<<5) is appending 5 to l and then printing l.

println(l+[6]) is creating a list that has all of the contents of l plus all of the contents on in the list that is on the right hand side of the + (in your case it just contains the number 6). Then that list is printed. That does not change the value or state of l.

Upvotes: 2

Related Questions