Are gradle scripts written in groovy?

I find it difficult to understand the groovy syntax in gradle.

If named parameters (in groovy) use the suffix : I assume that the code apply plugin: 'java' means calling the apply(plugin = 'java') function apply(plugin = 'java') . This is strange because the apply function is not even defined. Below is the error in my gradle script:

 println apply.getClass() > Could not get unknown property 'apply' for root project 'Simple' of type org.gradle.api.Project. 

So what is apply and where is it defined? Why doesn't the above code just print the apply element class?

And one more thing that is strange to me is the following:

 dependencies { compile 'org.slf4j:slf4j-api:1.7.12' testCompile 'junit:junit:4.12' } 

The syntax assumes that the code enclosed in {} is a closure, but what are the compile and testCompile ? If it was a close, then the code above would simply return 'junit:junit:4.12' as a string, and the rest should not be compiled. This seems to be more of a map definition. But then again, if the code above is data, then I would have to enter it into the groovysh shell.

 groovy:000> dependencies { compile 'org.slf4j:slf4j-api:1.7.12' testCompile 'junit:junit:4.12' } groovy:001> groovy:002> groovy:003> ERROR groovy.lang.MissingMethodException: No signature of method: groovysh_evaluate.dependencies() is applicable for argument types: (groovysh_evaluate$_run_closure1) values: [ groovysh_evaluate$_run_closure1@b7c4869 ] 

It bothers me. I thought gradle scripts are just groovy scripts, but it seems that DSL gradle is adding an element to the groovy language. A groovy clojure becomes a map, a function call with named parameters becomes something else.

Can someone enlighten me on this groovy DSL;)

+5
source share
2 answers
 plugin: 'java' 

is a groovy card. See the Project.apply () documentation and an explanation of this syntax in groovy .

Regarding dependencies, see DependencyHandler .

groovy is a very dynamic language where you can actually call undeclared methods and process a handler based on the name of the called method. AFAIK, that trick used here. See source code .

I'm not a groovy developer, and although I think DSL is elegant, I also sometimes find it confusing because it is difficult for me to associate some parts of DSL with specific methods in the documentation. But you eventually understand this and get used to it.

+3
source

compile 'org.slf4j:slf4j-api:1.7.12' not a map, it is a method call. In Groovy, you can omit the parentheses, so a call is equivalent to

 compile( 'org.slf4j:slf4j-api:1.7.12' ) 

Also, such methods in Gradle can take a second argument:

 compile( 'org.slf4j:slf4j-api:1.7.12' ){ exclude module:'log4j' } 

In this case, module:'log4j' is a card with missing square brackets, and the call can be rewritten as

 compile( 'org.slf4j:slf4j-api:1.7.12' ){ exclude( [module:'log4j'] ) } 
+2
source

Source: https://habr.com/ru/post/1267324/


All Articles