Skip to content
Tutorials Center
My learning

Topics

Lesson 108 of 134 ยท Testing and Tooling

Gradle Basics for Kotlin

Understand Gradle for Kotlin projects - build.gradle.kts, plugins, dependencies and coordinates, tasks and their dependency graph, source sets and version catalogs, with runnable models of how it works.

Up to now every program in this tutorial was a single file. A real project has hundreds of files, uses libraries written by other people, needs tests to run, and must be packaged for deployment. Someone has to compile files in the right order, download the libraries, run the tests, and produce the result. That someone is a build tool, and for Kotlin the standard one is Gradle.

This lesson explains what Gradle does and how to read a build.gradle.kts file. Gradle itself cannot run on this site, so the real build files are read-only examples. To make the ideas concrete we build small runnable models: a dependency coordinate parser, a build-script DSL like Gradle's own, and a task graph that skips work that is up to date. The other ingredients are the project structure and modules in the next lesson, and testing from the previous ones.

What a build tool does

A Gradle build answers four questions:

  1. What is the project? Its name, version, and the plugins that teach Gradle about Kotlin, applications or libraries.
  2. What does it depend on? Libraries and their versions. Gradle downloads them (and the libraries they need) from repositories such as Maven Central and caches them.
  3. What can be done? Tasks such as compileKotlin, test, jar, run, build.
  4. Where are the files? The folders with main and test code, by convention.

You describe the answers in Kotlin itself. The build script is called build.gradle.kts, where .kts marks a Kotlin script. (Older projects use Groovy, build.gradle; the Kotlin version gives you code completion and type checking in the IDE.)

The files of a project

A minimal Kotlin application looks like this on disk. This is a read-only listing:

TEXT
my-app/
  settings.gradle.kts        project name and modules
  build.gradle.kts           plugins, dependencies, tasks
  gradle.properties          optional settings (memory, flags)
  gradlew, gradlew.bat       the Gradle wrapper scripts
  gradle/
    wrapper/                 which Gradle version to use
    libs.versions.toml       optional version catalog
  src/
    main/kotlin/Main.kt      production code
    main/resources/          files bundled into the app
    test/kotlin/MainTest.kt  tests

The wrapper (gradlew) is the part that makes Gradle practical. It is a tiny script committed with the project that downloads the exact Gradle version the project needs. Nobody has to install Gradle first, and everyone, including the build server, uses the same version. Always run ./gradlew (or gradlew.bat on Windows), not a globally installed gradle.

A first build.gradle.kts

Here is a typical file. It is a read-only example, because it needs Gradle and network access:

Kotlin
// read-only example: build.gradle.kts
plugins {
    kotlin("jvm") version "2.4.21"
    application
}

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

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
    testImplementation(kotlin("test"))
}

kotlin {
    jvmToolchain(25)
}

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

tasks.test {
    useJUnitPlatform()
}

Going through it block by block:

  • plugins { } adds capabilities. kotlin("jvm") adds Kotlin compilation, source sets and the tasks compileKotlin and test. application adds run and packaging of a runnable program. The version is the Kotlin plugin version, which also fixes the compiler version.
  • group and version identify what you produce; they matter when you publish a library.
  • repositories { } says where to download from. mavenCentral() is the big public one.
  • dependencies { } lists the libraries, each with a configuration that says when it is needed (below).
  • kotlin { jvmToolchain(25) } says which JDK to compile with, so builds do not depend on whichever Java happens to be installed.
  • application { mainClass } names the class containing main. For a file Main.kt with fun main(), the generated class is MainKt, as you may remember from how Kotlin runs.
  • tasks.test { useJUnitPlatform() } tells the test task to use JUnit 5.

Settings file

settings.gradle.kts is short:

Kotlin
// read-only example: settings.gradle.kts
rootProject.name = "my-app"
// include(":core", ":app")      // for multi-module projects

Dependencies and coordinates

A library is named by three parts, its coordinates, written group:name:version. For example org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0 means group org.jetbrains.kotlinx, artifact kotlinx-coroutines-core, version 1.11.0. Gradle builds a URL from the coordinates, downloads the library and its own dependencies (transitive dependencies), and puts them on the classpath. The next example parses coordinates the way a build tool must.

Kotlin Parsing dependency coordinates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The jar path is org/jetbrains/kotlinx/kotlinx-coroutines-core/1.11.0/kotlinx-coroutines-core-1.11.0.jar, which is how Maven Central lays out files. The last line prints Expected group:name:version but got 'kotlinx-coroutines-core', which is the same kind of message Gradle gives for a malformed string.

Configurations: when is a dependency needed?

A dependency is added through a configuration, the keyword before the coordinate:

Configuration Meaning
implementation needed to compile and run this module; hidden from modules that depend on this one
api like implementation, but exposed to dependents (only with the java-library plugin)
compileOnly needed only at compile time (annotations, provided by the platform)
runtimeOnly needed only when running (a database driver)
testImplementation needed by tests only

Using implementation by default keeps your classpath small and your builds fast: when you change an internal library, modules that only use you do not need recompiling.

Versions are a classic source of pain. Two libraries may need different versions of a third; Gradle picks the highest by default and you can inspect the result with ./gradlew dependencies. Avoid dynamic versions like 1.+ or latest.release: a build must give the same result today and next month.

The build script is a DSL

The odd-looking blocks plugins { }, dependencies { } are not special syntax. They are ordinary Kotlin function calls with a lambda with receiver as the last argument: exactly the pattern from DSLs and builders. We can build a model of it ourselves.

Kotlin A build script DSL in 40 lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is com.example:1.0.0, then plugins: [org.jetbrains.kotlin.jvm, application], then the two dependencies with their configurations. Because the script is typed Kotlin, the IDE can suggest implementation inside dependencies { } and flag a typo. @DslMarker prevents a mistake you would otherwise make easily: calling an outer block's function from an inner one. See it fail:

Kotlin Wrong block in the DSL (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with main.kt:24:13: error: 'fun plugins(block: Plugins.() -> Unit): Unit' cannot be called in this context with an implicit receiver. Use an explicit receiver if necessary. Gradle's own DSL uses the same marker idea, which is why mixing up blocks is usually caught while you type. Move plugins { ... } out of dependencies { } and the program compiles.

Tasks and the task graph

Everything Gradle does is a task. You ask for one (./gradlew test) and Gradle first runs the tasks it depends on, in dependency order, and skips tasks whose inputs did not change. Common tasks from the Kotlin and application plugins:

Task Does
compileKotlin compiles src/main/kotlin
classes all main classes are ready (compile + resources)
test compiles and runs the tests
jar packages the classes into a jar
run runs the application (application plugin)
build everything: compile, test, package
clean deletes the build/ folder

The model below registers tasks with dependencies and remembers each task's last input. A task with unchanged input is reported UP-TO-DATE, exactly the message you see in Gradle's console output.

Kotlin A task graph with up-to-date checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first run executes compileKotlin, classes, test and build, in that order. The second run prints > Task :compileKotlin UP-TO-DATE and > Task :test UP-TO-DATE, because nothing changed, so it does almost no work. After the edit, compileKotlin and test run again. Last, the unknown task gives Task 'deploy' not found in root project 'demo'.

That is the heart of Gradle's speed. The real tool also keeps a build cache (results shared between machines), runs independent tasks in parallel and keeps a long-lived daemon process so the JVM does not start up cold each time. A build that took a minute at first often takes a couple of seconds the next time.

You can define your own tasks in the build script. This is read-only:

Kotlin
// read-only example: a custom task in build.gradle.kts
tasks.register("hello") {
    group = "demo"
    description = "Prints a greeting"
    doLast {
        println("Hello from Gradle, version $version")
    }
}

Run it with ./gradlew hello. Use ./gradlew tasks to list all tasks.

Source sets: where code lives

Gradle follows convention over configuration. The Kotlin plugin expects:

Folder Source set Purpose
src/main/kotlin main production code
src/main/resources main resource files (config, images)
src/test/kotlin test test code, sees the main classes
src/test/resources test test data

A source set is a group of source folders compiled together with its own classpath. The test source set can see main, but main can never see test. If you follow the layout, you write no configuration at all. The model below classifies paths the way the plugin would:

Kotlin Which source set does a file belong to?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first three lines print main code, main resources and test code; build.gradle.kts is not a source file, and the Scala file reports unknown folder 'scala'. In multiplatform projects, source sets multiply (commonMain, jvmMain, iosMain); see Kotlin Multiplatform.

Version catalogs

When a project has dozens of dependencies, scattering version strings across files is error prone. A version catalog, gradle/libs.versions.toml, collects them in one place. Read-only again:

TEXT
# read-only example: gradle/libs.versions.toml
[versions]
kotlin = "2.4.21"
coroutines = "1.11.0"

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

[plugins]
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }

and in build.gradle.kts:

Kotlin
// read-only example
plugins {
    alias(libs.plugins.kotlin.jvm)
}

dependencies {
    implementation(libs.coroutines.core)
}

The accessors libs.coroutines.core are generated, so you get completion and no typos. Updating a library then means changing one line.

Commands you will use

Terminal
# read-only example: run these in a project folder
./gradlew build            # compile, test, package
./gradlew test             # only the tests
./gradlew run              # run the application plugin's main class
./gradlew clean build      # delete outputs, then build
./gradlew dependencies     # print the dependency tree
./gradlew tasks            # list available tasks
./gradlew build --continue # report all failures, not just the first

The first build downloads Gradle, the libraries and the Kotlin compiler, so it is slow. Later builds are fast.

Common mistakes

  • Using a global gradle instead of the wrapper, so versions differ between machines.
  • Putting everything in api or implementation of one huge module. Split projects into modules and keep configurations tight (see project structure).
  • Dynamic versions (1.+), which make builds change on their own.
  • Forgetting useJUnitPlatform(), so JUnit 5 tests are silently not found.
  • Committing the build/ and .gradle/ folders. They are generated; add them to .gitignore.
  • Not pinning the JDK with a toolchain, so CI uses another Java than your laptop.
  • A wrong mainClass. The class for Main.kt is MainKt (plus the package name), not Main.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the three parts of a dependency coordinate?

    A coordinate such as org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0 is group:name:version.
  2. 2. Which configuration declares a library needed only by the tests?

    testImplementation puts the library on the classpath of the test source set only.
  3. 3. Why should you run ./gradlew instead of a globally installed gradle?

    The wrapper pins the Gradle version in the repository, so builds are reproducible for everyone.
  4. 4. What does > Task :compileKotlin UP-TO-DATE mean?

    Gradle compares the task's inputs with the previous run and skips the work if nothing changed.
  5. 5. Where does Gradle expect production Kotlin code by convention?

    src/main/kotlin holds production code and src/test/kotlin holds tests.

Summary

  • Gradle builds Kotlin projects: it resolves dependencies, compiles, tests and packages. The build script is Kotlin code in build.gradle.kts.
  • Always use the wrapper (./gradlew) so the Gradle version is pinned.
  • plugins, repositories, dependencies and the other blocks are Kotlin DSL calls (lambdas with receivers).
  • A dependency is group:name:version added through a configuration such as implementation or testImplementation.
  • Work is organized in tasks with dependencies; Gradle skips tasks that are UP-TO-DATE, and caches and parallelizes the rest.
  • Convention gives you src/main/kotlin and src/test/kotlin; version catalogs keep versions in one place.
  • Gradle itself is not available on this site, so the real build files are read-only and the runnable models above show the ideas.

Next: Project Structure and Modules