Call top level function from groovy method -


i figure has simple answer, web searching couldn't find it.

if i've got following (ideone):

def f() {}  class c {     public h() { f() } }  x = (new c()).h(); 

this fails following error:

no signature of method: c.f() applicable argument types: () values: [] 

how call f() inside method of c?

you need reference "outer" class (which isn't outer class).

assuming writing code in script.groovy file, generates 2 classes: c.class , script.class. there no way c call f() method, since has no idea defined.

you have options:

1) @michaeleaster's idea, giving metaclass defition current scope (i.e. script)

2) create/pass script object inside c:

def f() { "f" }  class c {     public h(s = new script()) { s.f() } }  assert "f" == new c().h() 

3) make c inner class (which needs instance of script:

class script {   def f() { "f" }    class c   {       public h() { f() }   }    static main(args) {     assert "f" == new c(new script()).h()   } } 

4) static inner class plus static f():

class script {   static def f() { "f" }    static class c   {       public h() { f() }   }    static main(args) {     assert "f" == new c().h()   } } 

Comments