Using closure as an argument to a superclass constructor

It seems I can not use Closure as a parameter for the constructor of the superclass when it is specified in a string.

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

Compilation failed with message Constructor call must be the first statement in a constructor..

I understand this is a somewhat strange use case, and so far I can create it around it. But it interests me, can this be expected? Or did I misunderstand the syntax?

+3
source share
2 answers

I think the problem is that Groovy is turning the constructor into something else, trying to compile it as a Java class. Perhaps the definition of closure expands to a call superthat generates this error.

:

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

, ...

super( { -> println 'called' } )
0

Source: https://habr.com/ru/post/1766813/


All Articles