Call plugin extension property becomes an assignment


(Baiyan Huang) #1

Code

class DemoExtension {
    String non_closure
    def override_closure = {}
}
  class DemoPlugin implements Plugin<Project> {
    void apply(Project project) {
        project.extensions.create('demoExtension', DemoExtension)
    }
}
  apply plugin: DemoPlugin
demoExtension {
    non_closure = "Hello"
    override_closure= {String jniPaths -> return ""}
    new_closure = {}
}
println "Non Closure:"
println demoExtension.non_closure
demoExtension.non_closure("hello, world")
println demoExtension.non_closure
  println "Override closure:"
println demoExtension.override_closure
demoExtension.override_closure("hello, world")
println demoExtension.override_closure
  println "New closure:"
println demoExtension.new_closure
demoExtension.new_closure("hello, world")
println demoExtension.new_closure

Output

Non Closure:
Hello
hello, world
Override closure:
build_7rtsbsk9dvhokdfj78dc5gki0k$_run_closure5_closure13@6cf26de4
hello, world
New closure:
build_7rtsbsk9dvhokdfj78dc5gki0k$_run_closure5_closure14@4aff7dfe
build_7rtsbsk9dvhokdfj78dc5gki0k$_run_closure5_closure14@4aff7dfe

Question: If a closure defined in the plugin extension, when I try to call it, it is actually an assignment statement, which set my closure to a weird value (which takes 0.5 day to diagnose), but if the closure is not predefined in the extension, it is actually calling the closure. Why would we want to support a function call like assignment in this case, is there a way to disable it?

Thanks.


(Peter Niederwieser) #2

It’s a known limitation. A safe way to call the closure (which presumably will be done by a (script) plugin) is ‘closure.call(arg)’.


(Baiyan Huang) #3

Thanks Peter, the behavior seems quite weird to me, when are we going to fix this?


(Peter Niederwieser) #4

It’s a consequence of the feature that ‘=’ can be omitted when setting a property.


(Baiyan Huang) #5

But if you look at the example above, new_closure = {} actually doesn’t have this problem, so is this a groovy limitation or gradle extension limitation?


(Peter Niederwieser) #6

It’s a feature of enhanced Gradle objects such as extensions, and hence also a limitation of them (when used with closures).


(Baiyan Huang) #7

Well, it seems this feature doesn’t provide much benefit, while is very easy to cause hard-to-identify problems, have you guys even consider to deprecate it?