Groovy syntax assignation

You can assign value to a property of a Gradle API class in two ways thanks to Groovy syntax (Is my assumption correct?). I see Gradle uses equals assign operator consistently through the examples (Testing in Java & JVM projects).

For example:

compileJava {
  sourceCompatibility = '15' // Gradle userguide convention 
  targetCompatibility '15'   // Also valid syntax 
}

What is the difference, and why should I use one over the other?

Is targetCompatibility really a method? I can’t find this method anywhere, just a getter and setter in AbstractCompile . I posted question on SO, while I am just more confused with the answer. groovy - Gradle equals assign operator vs space - Stack Overflow

Yes, techincally in your example targetCompatibility is a method call and sourceCompatibility is a property assignment.
But that’s just syntactic sugar Gradle automatically adds with the help of the extreme flexibilitly of the Groovy language.

It guess it was in a try to provide a more declarative syntax for the DSL.
And I guess in the user guide now the assignment syntax is preferred as then the Groovy and Kotlin examples are more similar as the same magic does not exist for the Kotlin DSL.

It really doesn’t matter which way you use, but you should choose one and stick with it for consistency.
I personal prefer the assignment, but actually I don’t use Groovy DSL anymore, but exclusively the Kotlin DSL because you instantly get type-safe build scripts, proper error messages if you mistype and amazing IDE support as well as better performance in some situations for the price of a bit worse performance in other situations but for the most part those are neglectible unless you have gigantic builds.

1 Like