0
  1. Looks like when you pass your List into a method/closure Groovy creates a copy of your List within the closure or method and updates that so your changes are not reflected once you exit!!! This is not the case if you use .add method

  2. Why would Groovy want to change this most intuitive of behaviour for a Java developer when you use addition with Lists with the operator overloaded + sign ?

  3. What would be the benefit from Groovy's point of view ?

  4. If I were to uncomment the enhanced for loops in my code sample and comment out the addition of Lists using the + sign - it behaves as expected

*

List<String> b = ['man', 'lady']

def x = { List<String> p ->

    println delegate.getClass().getName()
    List<String> inx = ['dog','cat']
    /*for (String l : inx)
    {
        p.add(l)
    }*/
    p = p + inx //value of p is not reflected whence you exit

}

def xmethod(List<String> p)
{
    List<String> inx = ['monkey','lion']
    /*for (String l : inx)
    {
      p.add(l)
    }*/
    p = p + inx // value of p is not reflected whence you exit

}

x( b )
println b

xmethod( b )
println b
user1561783
  • 483
  • 1
  • 4
  • 14

1 Answers1

0

Given: p = p + inx where p, inx are Lists

This can be read as: p = p.plus(inx), which in Groovy is an overloaded method that returns a new copy of the List passed in which of course will have a new address in memory. And therefore it does not update the List passed in.

When the method returns and comes of the stack the List created within is removed, and is no longer there.

Where you use p.plus(inx) or p + inx it is very important especially if p is passed into your method and you would like your changes to be reflected back to the original p that was passed in to use the p.addAll(inx) method instead.

BTW the same is true of Maps as well and I refer you to: Groovy (or Java) - Pass by reference into a wrapper object

user1561783
  • 483
  • 1
  • 4
  • 14