Defining Dependencies in Gradle Kotlin DSL

A concise syntax to define reusable dependencies

Gradle + Kotlin = Awesome

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.

This approach is exemplified by Jake Wharton’s U+2020 app, in which dependencies are pre-defined as Extra Properties:

Dependencies Definition in Groovy

It’s straightforward for Groovy-flavored Gradle scripts. However, it’ll be a bit different when it comes to Gradle Kotlin DSL (i.e. Gradle scripts written in Kotlin).

Kotlin compiler, which is statically typed, will complain about the following statement, which is the Kotlin equivalent of the dependency reference we wrote in the snippets above.

Kotlin Syntax Error

In fact, it has to be something like this:

🙀🙈 Well, it’s simply unacceptable!

I have to do some hackings to save my days. Fortunately, Kotlin has already given us powerful weapons: Extensions & Operator Overloading.

I’ll show you the result first and then explain the solution. The following snippet is the resulted syntax to define dependencies:

Dependency Definitions

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:

Dependency Retrieval

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 deps["support.appCompat"].

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.

🤝🖖

Software engineer, swimmer, scuba diver

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store