Defining Dependencies in Gradle Kotlin DSL
If you have a multi-module Gradle project (e.g. most Android projects), you may want to define all the dependencies in one place, then make references in sub-projects’ build file, keeping them consistent across the whole project.
In fact, it has to be something like this:
🙀🙈 Well, it’s simply unacceptable!
A Better Syntax
I’ll show you the result first and then explain the solution. The following snippet is the resulted syntax to define dependencies:
This’s the most concise syntax I can achieve. Optionally, the dependencies can be grouped recursively, with no limit.
The following is how we retrieve the dependencies later, please notice that a dot (
.) operator can be used to access grouped dependencies, square brackets are also supported:
Much better! 🎉
To achieve the above syntax, it’s not that difficult actually, couples of operators & extensions are enough to get the job done.
Firstly, build a tree structure to store the dependency definitions:
Equips the structure with operators to make the magic happen:
Finally, store the dependencies tree inside Extra Properties:
Done! 🍻 Now you have easy access to the dependencies by writing expressions like
Actually, what we just built is a simple DSL (domain-specific language), which we use to manage dependencies across multiple Gradle modules. And this is only the tip of an iceberg of the powerful Kotlin language features!
The complete code snippet can be found in this Gist. Put the files under the
buildSrc directory to enjoy the syntax sugar.
For those who are not familiar with
buildSrc, please refer to the Gradle User Guide.
I hope you enjoy the hacking, please let me know if you have any comments or better solutions.