Gradle build scripts use Groovy syntax. Gradle makes heavy use of Groovy closures, which are blocks of anonymous code that can take arguments, return values, and be assigned to variables. Looking at a sample Android project build file shows a similar structure using closures, with top-level functions like allprojects delegating to methods on the Project class.
4. A closure in Groovy is an open, anonymous, block of code
that can take arguments, return a value and be assigned to a
variable. A closure may reference variables declared in its
surrounding scope. In opposition to the formal definition of a
closure, Closure in the Groovy language can also contain free
variables which are defined outside of its surrounding
scope.
6. You don't have to include parameter types
in Groovy
def printStuff = { str -> println(str) }
printStuff("Hello Everybody!")
7. Methods can take closures as arguments:
executeClosure(printStuff)
// Create an inline closure and pass it as an argument
executeClosure({ println("I'm a closure")})
8. No parens needed if the method only
takes 1 argument:
executeClosure { println "I'm a closure" }
9. setDelegate can be used to change the context for the
closure being executed.
10. class DiscoveryOne {
def openDoors = { println "I'm afraid I can't do that" }
}
def enterSpaceship = {
openDoors()
}
DiscoveryOne spaceship = new DiscoveryOne()
enterSpaceship.setDelegate(spaceship)
enterSpaceship()
11. A look at a new Android project build file shows
something familiar looking.
allprojects {
repositories {
jcenter()
}
}
12. The allprojects function executes the given closure, which then
executes the repositories function (which is passed another
closure).
{
repositories {
jcenter()
}
}
Where is the repositories function defined?
13. The Project class
Docs
Most top level function calls delegate to the Project.
Inspect function declarations in Android Studio
• Right click -> Go To -> Declaration