Skip to main content

Using Code Autocomplete with build.gradle

This article was translated from Japanese by Claude Code.

When using Gradle Groovy DSL to define dependencies, you might think “it would be nice to have code completion.” You can use code completion by using Kotlin DSL instead of Gradle Groovy DSL.

I was under the impression that you needed to replace existing build.gradle files with build.gradle.kts to benefit from code completion. However, I learned that you can actually get autocomplete benefits with build.gradle files too by using buildSrc + import statements, so I’m documenting this.

Note that build.gradle.kts file definitions may become the mainstream in the future, so in that sense, this article may not be useful for the future, so please keep that in mind.

Create the buildSrc Directory
#

First, create the buildSrc directory. Create buildSrc/ directly under the project root. Example: your-project/buildSrc

Set Up Kotlin DSL
#

Next, place a build.gradle.kts file in the buildSrc directory. Example: your-project/buildSrc/build.gradle.kts

In this kts file, specify the dependency for the Kotlin DSL Plugin:

plugins {
    `kotlin-dsl`
}

repositories {
    mavenCentral()
}

Define Dependencies in a Dependencies.kt File
#

Next, create a Dependencies.kt file and define dependencies. Example: buildSrc/src/main/kotlin/dependnecies/Dependencies.kt

Since the package name is dependencies, specify it that way in the .kt file too:

package dependencies

object Depts {
    private const val VKOTLIN = "1.5.0"
    ...

    const val PLUGIN_KOTLIN = "org.jetbrains.kotlin:kotlin-gradle-plugin:$VKOTLIN"
    ...
}

That completes the definitions.

Using the Definitions
#

Finally, reference these definitions from your build.gradle file. For example, by referencing them like below, you can use autocomplete for Depts.~:

import dependencies.Depts // Add import statement

buildscript {
    repositories {
        google()
        mavenCentral()
        ...
    }
    dependencies {
        classpath Depts.PLUGIN_KOTLIN // You can use autocomplete here
    }
}

By the way, the above buildscript approach is now considered an old way. Reference: GitHub - Kotlin/kotlinx.serialization: Kotlin multiplatform / multi-format serialization

If you’re in a situation where existing projects only use build.gradle and you really want to use the autocomplete feature! I recommend giving this a try.

If you find any mistakes, please let me know in the comments!

References
#

【Android】buildSrcを使ってライブラリの定義をまとめる | ITcowork Staff Blog