Use Gradle function from other gradle file

3.4k views Asked by At

I want to split my 300 lines build.gradle logically into multiple build files to make it easier to maintain and extend.

As I've noticed, it is possible to split gradle tasks into multiple files and use them with:

apply from: "myGradleFile"

With this approach I sadly have no access to functions, defined in the second build script.

Is it also possible to split Gradle functions into multiple files?

Example:

Let's say I have my default build.gradle with a Task which uses a function

task doSomethingWithMyFunction {
    myFunction()
}

Now I have functions.gradle

def myFunction(){
}

So I want to access myFunction defined in functions.gradle from build.gradle

2

There are 2 answers

0
Opal On

It's not possible to be done with functions, but if you turn the functions into closures the following example will work well:

lol.gradle

project.ext.lolFunction = {
   println it
}

build.gradle

apply from: 'lol.gradle'

ext.lolFunction(1)                                                             
0
Robert Halter On

See 59.4 at https://docs.gradle.org/current/userguide/organizing_build_logic.html

You can move your functions to a

buildSrc

directory.