Reputation: 631
public updateList(lst) {
lst += "a"
}
List lst = []
updateList(lst)
println(lst)
This prints an empty list. However;
public updateList(lst) {
lst.add("a")
}
List lst = []
updateList(lst)
println(lst)
, will print "a" as desired.
I always assumed += was the same as .add(), but obviously not. I assume += is creating a new List, whereas .add() only updated the existing List?
Upvotes: 3
Views: 3069
Reputation: 171144
The first method calls plus
on the lst
variable
As we can see from the documentation this will:
Create a collection as a union of a Collection and an Object.
So a new collection will be returned, and the original lst
(outside the scope of this method) will be unchanged. (Obviously, inside this method's scope, lst will be a new list with one element)
This can be seen by printing out the result of the updateList
method:
public updateList(lst) {
lst += "a" // calls plus, creates a new list, and returns this new list.
// lst (outside the context of this method) is unmodified
}
List lst = []
println( updateList(lst) )
If you call add
, then you call the standard java add method.
public updateList(lst) {
lst.add "a"
}
So the original lst
is modified
An alternative to add
would be to use the leftShift
operator:
public updateList(lst) {
lst << "a"
}
Which calls add behind the scenes: (code from Groovy trunk source)
public static <T> Collection<T> leftShift(Collection<T> self, T value) {
self.add(value);
return self;
}
Upvotes: 7