Closure defined in root not visible in child

半城伤御伤魂 提交于 2019-12-10 22:45:22

问题


I have root project and subproject (:child). Root build looks like like this:

def foo = {
  println("foo")
}

allprojects {
  task bar << {
    println(project.name + ":bar")
  }

  afterEvaluate {
   foo()
  }
}

Running gradle bar prints:

foo
foo
:bar
:child:bar
child:bar
parent:bar

This make sense. However, IRL I need foo to be called by the child's build file (because I want it to be called only by some of the submodules). The documentation seems to be clear enough: In a multi-project build, sub-projects inherit the properties and methods of their parent project

However, moving the "afterEvaluate" block above into child/build.gradle results in an error: Could not find method foo() for arguments [] on project ':child' of type org.gradle.api.Project.

Why does this happen and how do I fix this? I have tried a whole bunch of different variations - moving the def around (to buildscript, allprojects, to ext, to allprojects.ext, making it a variable in ext, instead of a method etc.), referring to it differently (as rootProject.foo, rootProject.foo(), ext.foo() etc.) - nothing seems to work.

Any ideas?


回答1:


Vars need to be declared in the ext namespace for them to be propagated downstream. Try:

ext.foo = {
  println("foo")
}

ref: https://docs.gradle.org/current/dsl/org.gradle.api.plugins.ExtraPropertiesExtension.html



来源:https://stackoverflow.com/questions/41412975/closure-defined-in-root-not-visible-in-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!