Extract common methods from Gradle build script

Building on Peter's answer, this is how I export my methods:

Content of helpers/common-methods.gradle:

// Define methods as usual
def commonMethod1(param) {
    return true
}
def commonMethod2(param) {
    return true
}

// Export methods by turning them into closures
ext {
    commonMethod1 = this.&commonMethod1
    otherNameForMethod2 = this.&commonMethod2
}

And this is how I use those methods in another script:

// Use double-quotes, otherwise $ won't work
apply from: "$rootDir/helpers/common-methods.gradle"

// You can also use URLs
//apply from: "https://bitbucket.org/mb/build_scripts/raw/master/common-methods.gradle"

task myBuildTask {
    def myVar = commonMethod1("parameter1")
    otherNameForMethod2(myVar)
}

Here's more on converting methods to closures in Groovy.


I would suggest a slight adjustment to Matthias Braun's answer, in that instead of writing the same method-name twice and still have it clear and consise, why not simply do the following:

ext.commonMethod1 = (param) -> {
    return true
} as Closure<boolean>

The usage of the as-operator simply tells one explicitly, that this function will return a value of boolean-type.

Because after all, this still is Groovy goodness. Neat huh?


It isn't possible to share methods, but you can share extra properties containing a closure, which boils down to the same thing. For example, declare ext.foo = { ... } in common-methods.gradle, use apply from: to apply the script, and then call the closure with foo().


Using the Kotlin DSL it works like this:

build.gradle.kts:

apply {
  from("external.gradle.kts")
}

val foo = extra["foo"] as () -> Unit
foo()

external.gradle.kts:

extra["foo"] = fun() {
  println("Hello world!")
}