简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM