将闭包范围设置为调用方法

时间:2015-10-07 08:43:19

标签: groovy

是否可以将Groovy闭包的范围设置为调用方法?请参阅以下示例代码:

class TestClass {

  def testMethod() {
    def i = 42

    def closure = testClosure()
    closure.resolveStrategy = Closure.DELEGATE_FIRST 
    closure.delegate = this.&testMethod
    closure() // Should print 42.
  }

  def testMethod2() {
    def i = 43

    def closure = testClosure()
    closure.resolveStrategy = Closure.DELEGATE_FIRST 
    closure.delegate = this.&testMethod2
    closure() // Should print 43.
  }

  def testClosure = {
    println i // I get a MissingPropertyException: No such property i
  }
}

def test = new TestClass()
test.testMethod()
test.testMethod2()

1 个答案:

答案 0 :(得分:2)

不,但您可以将i移动到与闭包相同的范围:

class TestClass {

  def i

  def testMethod() {
    i = 42
    testClosure() // Should print 42.
  }

  def testMethod2() {
    i = 43
    testClosure() // Should print 43.
  }

  def testClosure = {
    println i // I get a MissingPropertyException: No such property i
  }
}

def test = new TestClass()
test.testMethod()
test.testMethod2()