Search code examples
gradlegradle-kotlin-dsl

Best way to re-use a function across Gradle submodules


I defined a Kotlin function in one of my submodules to load some environment variables from a file. I now want to use this function in other submodules as well, but define it only once. I can achieve this using a buildSrc dir. But to me it seems overkill to have an entire buildSrc/ just for one function. Is this the recommended way to achieve what I want or is there a better way?


Solution

  • Using buildSrc is the fastest way of sharing code across your build files.

    Each build is a separate JVM program. To share code, each of those builds needs the shared code as a separate compiled dependency, which needs to be built in turn. That means that shared code needs its own separate compilation. buildSrc provides a straightforward means of setting up such a separate shared compilation.

    The great benefit of Gradle is the whole thing is written on the JVM, so there is huge power to do whatever you want. But the flip side of that is you need to arrange things so that the associated code compilation can take place. Other build tools using configuration files will likely need a bit less setup, but you sacrifice that power.

    All in all, it's just a folder and and a few files. It won't take you very long to create them and you will reap the benefits of sharing that code.