I just can’t figure out what happens when I write a property in plugin extension closure. Say, I have a sample plugin and I want to initialize some properties on plugin
sample {
prop “some prop” // what happens here? Is this calling a function with string as arg?
}
or I can also write it as
sample {
prop = “some prop” // which is just assigning value to prop
}
I recommend reading Groovy’s closure guide. More specifically, the sub-section about delegation strategy. There you’ll see more precisely which object is being used to find the properties and methods.
To answer your questions: yes, you’re right, but AFAIK the examples are different. In the first case, like you said, you’re calling a method called prop(String s) (either from the closure owner, or from the closure delegate). In the second case, you’re setting a property prop (which means it’s calling a different method setProp(String s)).
If the property is not found (the delegation strategy defines the search order), then I’m not exactly sure what happens, but I believe it calls a generic method setProperty(String name, Object value).
Thanks for the link jvff. It was very helpful. I have written this small program to understand the concept.
class User {
int age
String name // by default field are private. Classes and methods are public
String email
String location
String profession
void name(String value){
this.name = value
}
void someMethod(Closure c){
c()
}
}
main class
class App {
static void main(String[] args){
User obj = new User (name: "username", age: 21, location: "mock location", profession: "developer", email: "aaaa@gmail.com")
def user = {
name "allaudin" // method call, same as name(arg)
name = "qazi" // assigned directly to field using default setter.
println "$name, $age, $location"
someMethod {
println "some method called."
}
}
user.delegate = obj
user.resolveStrategy = Closure.DELEGATE_FIRST
user()
}
}
And to explain where these methods come from: Gradle adds those at runtime for every setter on a domain object. So whenever you can write foo = 'bar' you can also write foo 'bar'.