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?
The first method calls
pluson thelstvariableAs we can see from the documentation this will:
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
updateListmethod:If you call
add, then you call the standard java add method.So the original
lstis modifiedAn alternative to
addwould be to use theleftShiftoperator:Which calls add behind the scenes: (code from Groovy trunk source)