Thuta Learning
Kotlin
AdvancedProgrammingBeginner

Gradle, Dependencies & Project Structure

KotlinLesson 2640 min

What you'll walk away with

  • Read settings.gradle.kts and build.gradle.kts and say what each block (plugins, repositories, dependencies) does
  • Place source files in src/main/kotlin and src/test/kotlin and explain why that layout is a convention
  • Choose between implementation, testImplementation, runtimeOnly and compileOnly for a dependency
  • Predict which version Gradle picks when two libraries ask for different versions of the same module
  • Run ./gradlew build, test and run, and explain why Gradle skips tasks that are up to date

Explain it simply

Gradle in plain language

Gradle is the build tool behind most Kotlin projects. You describe the project in a few small files, and Gradle works out what to download, what to compile and in which order, and what it can skip because nothing changed. Think of a site manager: you hand over the blueprint (build.gradle.kts) and the list of suppliers (repositories and dependencies), and the manager schedules every job after the jobs it depends on.

You run Gradle through a small script that lives inside your repository, the Gradle Wrapper: ./gradlew on macOS and Linux, gradlew.bat on Windows. Because the wrapper downloads the Gradle version the project asks for, every teammate and every CI machine builds with exactly the same tool, without installing anything by hand.

Problem → Why → Solution

The problem: a hand-rolled build

Without a build tool, 'it works on my machine' becomes a way of life. A teammate needs the same library jars in the same versions, compiled with the same JDK. Test classes must not end up in the shipped jar. A second module has to be compiled before the first one can use it. Doing this by hand with kotlinc and copied jars means every new library is a manual download, every upgrade is a hunt for the jars it needs in turn, and the build instructions live in somebody's head or in a README nobody updates.

The script below is a typical hand-rolled attempt. It works only where the files happen to be in the right places, it knows nothing about the library's own dependencies, and it has no idea what to do about tests.

build.sh
# hand-rolled build: works only on the machine that has these exact files
kotlinc src/main/kotlin/*.kt -cp libs/library-a.jar:libs/library-b.jar -d out
java -cp out:libs/library-a.jar:libs/library-b.jar MainKt

# Where are the tests? The jars library-a itself needs? The second module?
# Nobody remembers, and a new teammate has to guess.

A build is really a graph problem

Libraries depend on libraries, modules depend on modules, and tasks depend on tasks. A build tool stores that graph in a declarative file, downloads each node once from a repository, and runs the nodes in an order that respects every arrow. Once the graph is data, you can ask questions of it: what changed, what must be rebuilt, and which version of a shared library wins.

Core concept: files, layout, dependencies and tasks

A Gradle project is controlled by a few files at its root. settings.gradle.kts names the root project and lists the modules it contains with include(...). build.gradle.kts, one per module, declares the plugins to apply, the repositories to download from, the dependencies and any task configuration. gradle/libs.versions.toml is an optional version catalog that keeps library versions in one place. The .kts extension means a Kotlin script, so the editor can autocomplete and type-check it (Gradle also accepts the Groovy DSL, build.gradle). The wrapper files gradlew, gradlew.bat and gradle/wrapper/ belong in version control; the build/ and .gradle/ folders do not.

The Kotlin JVM plugin follows a convention for where files live: production code goes in src/main/kotlin, resources in src/main/resources, and tests in src/test/kotlin. Those folders are the main and test source sets. Packages normally mirror folders, so com.example.shop.Cart sits in src/main/kotlin/com/example/shop/Cart.kt. Gradle writes compiled classes and jars to build/, which you can delete at any time because it is regenerated.

A dependency is written as group:artifact:version, for example org.jetbrains.kotlinx:kotlinx-coroutines-core:<version>, and Gradle looks for it in the repositories you declare, usually mavenCentral(). The configuration you choose says where the library is visible: implementation puts it on this module's compile and runtime classpath without exposing it on the compile classpath of modules that depend on you, testImplementation makes it available only to tests, runtimeOnly adds it only when the program runs, and compileOnly only while compiling. Libraries bring their own dependencies along (transitive dependencies), and when two paths ask for different versions of the same module, Gradle's default is to pick the highest requested version.

Everything Gradle does is a task: compileKotlin, compileTestKotlin, test, jar and so on. Tasks form a graph in which test needs classes which needs compileKotlin, and Gradle runs only what the requested task needs. A run has three phases: initialization reads settings.gradle.kts, configuration evaluates every build.gradle.kts to build the task graph, and execution runs the selected tasks. A task whose inputs and outputs are unchanged is skipped and reported as UP-TO-DATE, which is why a second build is much faster than the first.

CommandWhat it does
./gradlew buildcompiles, tests and assembles everything
./gradlew testcompiles and runs the test source set
./gradlew runstarts the application (needs the application plugin)
./gradlew dependenciesprints the resolved dependency tree
A build is a graph of tasks
  1. settings.gradle.kts picks the modules
  2. build.gradle.kts declares plugins, deps
  3. Gradle resolves versions, downloads jars
  4. Tasks run after the tasks they need

If you can draw the arrows between modules and tasks, you can predict the build order and what a change will rebuild.

General pattern

build.gradle.kts
plugins {
    kotlin("jvm") version "<kotlin-version>"
}

repositories { mavenCentral() }

dependencies {
    implementation("group:artifact:version")
    testImplementation(kotlin("test"))
}

tasks.test { useJUnitPlatform() }

plugins says what to apply, repositories says where to download from, and dependencies says what the code needs. These are declarative blocks that tell Gradle what you want; they do not run your program.

Worked example: a build graph in plain Kotlin

Real Gradle scripts cannot run on this page, so the worked example models two things Gradle does for you: ordering modules so that dependencies build first, and choosing the highest version when several dependencies ask for the same library. The code is ordinary Kotlin with check() assertions, so you can run it and change the module list to see how the order and the cycle error react.

The real thing is more detailed

Gradle compares versions with more rules than this model, for example qualifiers such as -rc or -SNAPSHOT, and you can also ask it to insist on one exact version. The numeric comparison here is enough to show the idea: 2.10.0 is newer than 2.9.9 even though the text '2.9.9' sorts after '2.10.0'.

BuildGraph.kt
data class Module(val name: String, val dependsOn: List<String> = emptyList())

fun buildOrder(modules: List<Module>): List<String> {
    val byName = modules.associateBy { it.name }
    val order = mutableListOf<String>()
    val state = mutableMapOf<String, Int>() // 1 = being visited, 2 = finished

    fun visit(name: String, path: List<String>) {
        if (state[name] == 2) return
        check(state[name] != 1) {
            "circular dependency: " + (path + name).joinToString(" -> ")
        }
        val module = byName[name] ?: error("unknown module '$name'")
        state[name] = 1
        module.dependsOn.forEach { visit(it, path + name) }
        state[name] = 2
        order += name
    }

    modules.forEach { visit(it.name, emptyList()) }
    return order
}

fun compareVersions(a: String, b: String): Int {
    val x = a.split(".").map { it.toInt() }
    val y = b.split(".").map { it.toInt() }
    for (i in 0 until maxOf(x.size, y.size)) {
        val diff = x.getOrElse(i) { 0 }.compareTo(y.getOrElse(i) { 0 })
        if (diff != 0) return diff
    }
    return 0
}

fun resolve(requests: List<Pair<String, String>>): Map<String, String> =
    requests.groupBy({ it.first }, { it.second }).mapValues { (_, versions) ->
        versions.maxWith { a, b -> compareVersions(a, b) }
    }

fun main() {
    val modules = listOf(
        Module("app", listOf("feature", "core")),
        Module("feature", listOf("core")),
        Module("core"),
    )
    val order = buildOrder(modules)
    println("build order: " + order.joinToString(" -> "))
    check(order.indexOf("core") < order.indexOf("feature"))
    check(order.last() == "app")

    val cyclic = listOf(Module("app", listOf("core")), Module("core", listOf("app")))
    try {
        buildOrder(cyclic)
    } catch (e: IllegalStateException) {
        println(e.message)
    }

    val requests = listOf(
        "json" to "2.9.1",
        "json" to "2.10.0",
        "log" to "1.2.0",
        "json" to "2.9.9",
    )
    val resolved = resolve(requests)
    check(resolved["json"] == "2.10.0")
    check("2.9.9" > "2.10.0") // plain string comparison gets this wrong
    resolved.forEach { (module, version) -> println("$module -> $version") }
}

Code breakdown

  1. Modules form a graphdata class Module(val name: String, val dependsOn: List<String> = emptyList())

    Each module is a name plus the list of modules it depends on. It is the same information you write in Gradle as implementation(project(":core")).

  2. Dependencies firstmodule.dependsOn.forEach { visit(it, path + name) }

    A module is added to the order only after its dependencies are finished, which puts core before feature and feature before app.

  3. Cycles are errorscheck(state[name] != 1) {

    Meeting a module that is already on the current path (state 1) means a cycle. If modules depend on each other, as in app -> core -> app, there is no valid first one, so the build is refused.

  4. Newest version winsversions.maxWith { a, b -> compareVersions(a, b) }

    All versions requested for one module are collected and the highest is kept, which mirrors Gradle's default conflict resolution.

  5. Numeric comparisonx.getOrElse(i) { 0 }.compareTo(y.getOrElse(i) { 0 })

    The version is split at '.' and each part is compared as a number, so 10 beats 9 and 2.10.0 beats 2.9.9. A missing part counts as 0.

  6. Assert the resultcheck(order.last() == "app")

    main does not just print the result; it asserts it with check(). If the rule that app builds last is ever broken, the program fails at once.

You should see
build order: core -> feature -> app
circular dependency: app -> core -> app
json -> 2.10.0
log -> 1.2.0
What ./gradlew test does
  1. Read settings.gradle.kts and find the modules
  2. Evaluate build scripts and build the task graph
  3. Resolve dependencies from the repositories
  4. Compile main, compile test, run the tests
  5. Report results; skip tasks that are UP-TO-DATE

A complete single-module build

The build.gradle.kts below has everything a Kotlin/JVM application needs. kotlin("jvm") applies the Kotlin Gradle plugin; check the official release page for the current version instead of guessing. The application plugin adds the run task, and mainClass is the entry point (a top-level main() in Main.kt becomes the class MainKt). jvmToolchain(21) states which JDK to compile and test with, and useJUnitPlatform() runs the tests on the JUnit Platform.

build.gradle.kts
plugins {
    kotlin("jvm") version "2.1.21"   // check the current Kotlin version
    application
}

group = "com.example"
version = "1.0.0"

repositories {
    mavenCentral()
}

dependencies {
    // replace <version> with the current kotlinx.coroutines release
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:<version>")
    testImplementation(kotlin("test"))
}

kotlin {
    jvmToolchain(21)
}

application {
    mainClass.set("com.example.MainKt")
}

tasks.test {
    useJUnitPlatform()
}
settings.gradle.kts
rootProject.name = "task-app"
project layout
task-app/
  settings.gradle.kts
  build.gradle.kts
  gradlew
  gradlew.bat
  gradle/wrapper/
    gradle-wrapper.jar
    gradle-wrapper.properties
  src/
    main/
      kotlin/com/example/Main.kt      -> compiled to class MainKt
      resources/
    test/
      kotlin/com/example/MainTest.kt
  build/                              -> generated, never commit

A version catalog: one place for versions

With five or ten libraries, version numbers scattered through build scripts drift apart. In gradle/libs.versions.toml you declare versions and libraries once, and scripts use type-safe accessors such as libs.coroutines.core. Libraries that must move together, such as kotlinx-coroutines-core and kotlinx-coroutines-test, point at the same version.ref, so they cannot diverge.

gradle/libs.versions.toml
[versions]
kotlin = "2.1.21"
coroutines = "<version>"

[libraries.coroutines-core]
module = "org.jetbrains.kotlinx:kotlinx-coroutines-core"
version.ref = "coroutines"

[libraries.coroutines-test]
module = "org.jetbrains.kotlinx:kotlinx-coroutines-test"
version.ref = "coroutines"

[plugins.kotlin-jvm]
id = "org.jetbrains.kotlin.jvm"
version.ref = "kotlin"
build.gradle.kts
plugins {
    alias(libs.plugins.kotlin.jvm)
    application
}

dependencies {
    implementation(libs.coroutines.core)
    testImplementation(libs.coroutines.test)
    testImplementation(kotlin("test"))
}

Several modules

As a project grows you split it into modules such as :core, :data and :app. settings.gradle.kts lists them with include, and one module depends on another with implementation(project(":core")). Those arrows are the Module.dependsOn from the worked example: if :app depends on :core, the core tasks run first, and changing only :core recompiles :core and the modules that depend on it. Splitting modules sensibly makes builds faster.

settings.gradle.kts, build.gradle.kts, app/build.gradle.kts
// settings.gradle.kts
rootProject.name = "task-app"
include(":core", ":app")

// build.gradle.kts (root): declare the plugin once, apply it per module
plugins {
    kotlin("jvm") version "2.1.21" apply false
}

// app/build.gradle.kts
plugins {
    kotlin("jvm")
    application
}

dependencies {
    implementation(project(":core"))
}

Day-to-day commands

Run these from the project root. A task of a single module is addressed with a prefix such as :core:test, and dependencyInsight explains why a library ended up with a particular version, which is the tool for investigating conflicts.

terminal
./gradlew build            # compile, test, assemble
./gradlew test             # only the tests
./gradlew :core:test       # the tests of one module
./gradlew run              # start the application
./gradlew dependencies     # the resolved dependency tree
# why did this library get this version?
./gradlew dependencyInsight --dependency coroutines --configuration runtimeClasspath
./gradlew clean build      # delete build/ first, then rebuild everything

In real projects

Where Gradle shows up in real projects

Sooner or later every Kotlin developer meets Gradle. Projects usually start from a generator rather than from a blank file, and understanding the build files is what lets you fix problems when something breaks.

  • Android: Android Studio projects use Gradle together with the Android Gradle Plugin, each module has a build.gradle.kts (or build.gradle), and adding a library is one line in the dependencies block.
  • Server frameworks: the Spring Boot and Ktor project generators produce build files for Kotlin with Gradle as an option, and the generated files look like the patterns in this lesson.
  • CI: on every pull request the CI server runs ./gradlew build and blocks the merge if a test fails; thanks to the wrapper, CI does not need a separate Gradle installation.
  • Multi-module projects: with modules such as :core, :data and :feature, only the changed module and the modules depending on it are recompiled, and the build cache skips the rest.

Common mistakes

Common mistakes with Gradle

Declaring a test library with implementation

Writing implementation(kotlin("test")) puts the test library on the production classpath, so it can end up inside the application you ship. If a library is only for tests, use testImplementation so the main source set cannot see it.

Letting related libraries drift apart in version

Declaring kotlinx-coroutines-core at 1.9 and kotlinx-coroutines-test at 1.10 by accident can cause odd runtime errors. Keep versions in one place in the version catalog and let libraries that belong together share one version.ref.

Committing build/ but not the wrapper

If gradlew, gradlew.bat and gradle/wrapper/ are not in the repository, each teammate may use a different Gradle version and the 'works on my machine' problem returns. The opposite mistake is committing build/ and .gradle/: the generated files clutter diffs and cause conflicts, so put them in .gitignore.

Making modules depend on each other in a circle

If :core depends on :app while :app depends on :core, neither can be built first and Gradle stops with a circular-dependency error. The fix is to move the shared part into a third module; the check() in the worked example catches exactly this shape.

Best practices

Best practices

  • Always use ./gradlew rather than a Gradle installed on your machine, so the project and CI run the same Gradle version.
  • Keep library versions in a version catalog and let build scripts refer only to that catalog.
  • Declare each dependency with the narrowest scope that works: testImplementation for tests, implementation for most others.
  • When a version conflict is suspected, check with ./gradlew dependencies or dependencyInsight instead of guessing.

Mini challenge

Mini challenge: what must be rebuilt when a module changes?

Given a module graph and one changed module, write affectedBy, which returns every module that must be rebuilt: the changed module itself and every module that depends on it, directly or indirectly. Gradle's incremental builds rest on this idea.

  • affectedBy(changed, modules) returns a Set<String> that includes changed itself
  • Include indirect dependents too (app -> feature -> core)
  • Do not include unrelated modules such as tools
  • In main, print the results for changing core, feature and tools, and use check() for app and tools
Affected.kt
data class Module(val name: String, val dependsOn: List<String> = emptyList())

// TODO: start from the changed module, then keep adding every module that
//       depends on something already in the set, until nothing new appears
fun affectedBy(changed: String, modules: List<Module>): Set<String> {
    TODO()
}

fun main() {
    val modules = listOf(
        Module("app", listOf("feature", "data")),
        Module("feature", listOf("core")),
        Module("data", listOf("core")),
        Module("core"),
        Module("tools"),
    )
    // TODO: print affectedBy for "core", "feature" and "tools" (sorted)
    // TODO: check() that changing "app" affects only app, and that "tools" is
    //       not affected by a change in "core"
}

Expected: Changing core prints [app, core, data, feature], changing feature prints [app, feature], and changing tools prints [tools].

Show hint

Start a set with changed, then loop: look at every module and add it when one of its dependsOn entries is already in the set and it is not in the set yet. Repeat until the set stops growing and the indirect dependents come along.

Show solution
Affected.kt
data class Module(val name: String, val dependsOn: List<String> = emptyList())

fun affectedBy(changed: String, modules: List<Module>): Set<String> {
    val result = mutableSetOf(changed)
    var grew = true
    while (grew) {
        grew = false
        for (module in modules) {
            if (module.name !in result && module.dependsOn.any { it in result }) {
                result += module.name
                grew = true
            }
        }
    }
    return result
}

fun main() {
    val modules = listOf(
        Module("app", listOf("feature", "data")),
        Module("feature", listOf("core")),
        Module("data", listOf("core")),
        Module("core"),
        Module("tools"),
    )
    println("core changed    -> " + affectedBy("core", modules).sorted())
    println("feature changed -> " + affectedBy("feature", modules).sorted())
    println("tools changed   -> " + affectedBy("tools", modules).sorted())
    check(affectedBy("app", modules) == setOf("app"))
    check("tools" !in affectedBy("core", modules))
}

Quick quiz 1 / 3

Which file lists the modules of a multi-module Gradle build?

Quick quiz 2 / 3

A test library is declared with implementation(...) instead of testImplementation(...). What is the consequence?

Quick quiz 3 / 3

Two dependencies ask for the json library at 2.9.9 and 2.10.0. By default, which version does Gradle put on the classpath?

What to remember

  • settings.gradle.kts selects the modules and build.gradle.kts declares plugins, repositories and dependencies.
  • Sources live in src/main/kotlin and src/test/kotlin, and build/ is regenerated output that is never committed.
  • implementation, testImplementation, runtimeOnly and compileOnly decide where a dependency is visible, and on a version conflict Gradle picks the highest.
  • Gradle runs a task graph and skips unchanged tasks as UP-TO-DATE; use the ./gradlew wrapper.

Kotlin releases — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.