使用Closure作为超类构造函数的参数

时间:2010-09-27 17:24:33

标签: groovy

当内联指定时,我似乎无法将Closure用作超类构造函数的参数。

class Base {

  def c

  Base(c) {
    this.c = c
  }

  void callMyClosure() {
    c()
  }
}

class Upper extends Base {
  Upper() {
    super( { println 'called' } )
  }
}

u = new Upper()
u.callMyClosure()

编译失败,显示消息Constructor call must be the first statement in a constructor.

我意识到这是一个有点奇怪的用例,我可以暂时围绕它进行设计。但我很感兴趣,这是可以预料的吗?或者我的语法不正确?

2 个答案:

答案 0 :(得分:1)

我认为这个问题与Groovy在尝试将其编译为Java类时将构造函数转换为不同的事实有关。在调用super生成该错误之前,可能会扩展闭包定义。

解决方法是在构造函数本身之外定义闭包:

class Base {
  def c

  Base(c) {this.c = c}


  void callMyClosure() {
    c()
  }
}

class Upper extends Base {
  static cc = {println 'called'}

  Upper() {
    super(cc)
  }
}

u = new Upper()
u.callMyClosure()

它不是那么好但至少它可行..另一种方法是使用普通的new Closure(...)语法来定义闭包

答案 1 :(得分:0)

它可能会让一个闭包和一个块感到困惑......你可以试试吗

super( { -> println 'called' } )
相关问题