【问题标题】:Strange behavior of groovy closures referencing class field引用类字段的 groovy 闭包的奇怪行为
【发布时间】:2014-04-11 09:24:44
【问题描述】:

这是一个代码示例:

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

如您所见,printsNothingprintsList 中的闭包是相同的,但结果不同,因为 printsNothing 确实没有打印任何内容,就好像 list 是空的一样。这是输出:

Expected: 
1
2
3
Strange: 

我正在使用启用了调用动态支持的 Groovy 2.2.2。

关于这是一个错误还是我对 Groovy 一无所知的任何建议?

【问题讨论】:

    标签: groovy closures


    【解决方案1】:

    这是在user mailing list recently 上,这是因为它在空列表(和[].list == [])的所有元素中寻找属性list。如果将printsNothing 方法更改为:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      相关资源
      最近更新 更多