Andy
Andy

Reputation: 1484

Strange behavior of groovy closures referencing class field

Here's a code sample:

class StaticTest {

  static def list = [1, 2, 3]

  void printsNothing() {
    [].with { list.each { println it } }
  }

  void printsList() {
    new Object().with { list.each { println it } }
  }

  public static void main(String[] args) {
    new StaticTest().with {
      println "Expected: "
      printsList()

      println "Strange: "
      printsNothing()
    }
  }
}

As you can see, closures in printsNothing and printsList are identical, nevertheless the result differs as printsNothing indeed prints nothing as if the list was empty. Here's the output:

Expected: 
1
2
3
Strange: 

I'm using Groovy 2.2.2 with invokedynamic support enabled.

Any suggestions on whether this is a bug or I just know nothing about Groovy?

Upvotes: 0

Views: 49

Answers (1)

tim_yates
tim_yates

Reputation: 171054

This was on the user mailing list recently, it's because it's looking for the property list in all of the elements of the empty list (and [].list == []). If you change the printsNothing method to:

void printsNothing() {
    // Use this.list to get round local `with` scoping
    [].with { this.list.each { println it } }
}

Upvotes: 2

Related Questions