Groovy List Issues with options: + = doesn't work, but .add () does

public updateList(lst) {
  lst += "a"
}

List lst = []
updateList(lst)
println(lst)

Prints an empty list. Nonetheless,

public updateList(lst) {
  lst.add("a")
}

List lst = []
updateList(lst)
println(lst)

prints a as desired.

I always assumed that + = was the same as .add (), but obviously not. I assume + = creates a new list, whereas .add () only updated the existing list?

+3
source share
1 answer

The first method calls plusin a variablelst

As we can see from the documentation , this will be:

Create a collection as a union Collection and object.

, , lst ( ) . (, lst )

, updateList:

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) )

add, java.

public updateList(lst) {
  lst.add "a"
}

, lst

add leftShift:

public updateList(lst) {
  lst << "a"
}

: ( Groovy )

public static <T> Collection<T> leftShift(Collection<T> self, T value) {
    self.add(value);
    return self;
}
+7

Source: https://habr.com/ru/post/1756724/


All Articles