How to access projects in multimodule Gradle project?

Aldo WachyudiAldo Wachyudi
2 min read

In a multimodule Gradle project, you're likely to have.. many modules. Each module can have other modules as dependencies.

dependencies {
    implementation(project(":feature:feature-payment"))
    implementation(project(":lib:crypto"))
    implementation(project(":android-lib:navigation"))    
}

How would you remember the module name, if you have 100 modules?

An example of multimodule project called nowinandroid

Sure, you can type the module name manually, like in the above code snippet. But is there a safer and faster way to access the project? Yes, there is!

By using Gradle's TYPESAFE_PROJECT_ACCESSORS, we can access the projects in our project in a typesafe way.

If your project exists, the IDE will give autocomplete.

autocomplete

If your project doesn't exist, the IDE will give you an error.

Setup

  1. Make sure you're using Gradle 7.0 or higher
  2. In your root project build.gradle file, add the following line of code.
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")

Result

Open your build.gradle or build.gradle.kts, the dependencies above will look like this.

dependencies {
    implementation(projects.feature.featurePayment)
    implementation(projects.lib.crypto)
    implementation(projects.androidLib.navigation)    
}

Notice that Gradle converts the module with kebab-case or snake_case to camelCase. From feature-payment to featurePayment.

Summary

By using typesafe project accessors you can access modules in your project in a typesafe manner. Currently, Gradle still marks this feature as experimental. But you can use it in your project by enabling the TYPESAFE_PROJECT_ACCESSORS in the build.gradle file.

References:

2
Subscribe to my newsletter

Read articles from Aldo Wachyudi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aldo Wachyudi
Aldo Wachyudi

Aldo is a mobile engineering manager at Astro, a quick commerce company in Indonesia. He started at a startup, went on to lead Android team at LINE, and now working at Astro. He is currently managing Android, iOS, and React Native teams for customer-facing apps. He is passionate about designing testable code, writing clear documentation, and building apps at scale. When he is not writing an article or playing with the latest technology, you'll find him learning about coffee making or contributing to the local community.