Home > other >  Dependency syntax of Gradle build script in Groovy
Dependency syntax of Gradle build script in Groovy

Time:06-19

For example the Groovy code like this:

dependencies {
    classpath 'com.android.tools.build:gradle:0.13.2'
}

I know classpath is a function and you invoke it by passing a string
But my questions are:

  1. Is dependencies is a method of object project?
  2. Is classpath a method of project or dependencies?
  3. What does it mean when you pass a closure to a function?

CodePudding user response:

Try looking at the API docs, or navigating through the source. It helps to get your head around it. That said, there are all sorts of other things going on with delegates/owners and such, so it's not always clear on inspection where things are being called if you're not used to this aspect of Groovy. The descriptions and examples in the docs are likely going to be more useful for general usage.

dependencies is a method on Project, and is of type DependencyHandler. (Many if not most things you use frequently will live on Project) https://docs.gradle.org/current/javadoc/org/gradle/api/Project.html#dependencies-groovy.lang.Closure- https://docs.gradle.org/current/javadoc/org/gradle/api/artifacts/dsl/DependencyHandler.html

In the dependencies block the add method of DependencyHandler gets called, with a 'configuration' and the dependency string. classpath here is a configuration used for the buildscript itself

What does it mean when you pass a closure to a function?

It means just that. Closure is a class in Groovy, and when you write this in Gradle you are creating a new closure and passing it as a parameter to a function (see the docs above, they reference Closure as a param in many methods). The Groovy docs can explain how they work better than I can. You can sort of think of it as a lambda, but it's not the same. It can execute code on its owner (usually the enclosing block/closure it's defined in) and can sometimes execute against its assigned delegate. If you're trying to work out how the Gradle configs work internally, usually you can find most of what you need on the class as above (e.g. mostly we're calling methods on DependencyHandler in this case). However the written documentation covers most common use cases.

  • Related