Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Gradle Build

Kotlin Gradle Build

Gradle is currently the most widely used build tool for Kotlin/JVM projects; it compiles source code, manages third-party dependencies, runs tests, and packages artifacts.

This chapter builds a Kotlin Gradle project from scratch, explaining how to write build.gradle.kts, the differences between dependency configurations, and common commands.


Why use Gradle

Compiling a few Kotlin files with kotlinc is enough, but a real project involves far more than just compiling.

You need to bring in third-party libraries, separate main code from test code, split the project into multiple modules, and produce artifacts for different environments when packaging; doing all this by hand is tedious and error-prone.

Gradle turns these tasks into repeatable "tasks" that can be completed with a single command.

Compared with Maven, Gradle uses Kotlin DSL or Groovy DSL for configuration; the build file is itself code, allowing loops, conditionals, and custom functions, making it more flexible.

Both the official Kotlin documentation and the official Android documentation use Gradle as the default build solution, so new projects barely need to consider other options.

Capability Description Typical scenario
Dependency Management Automatically download and resolve third-party libraries, handling transitive dependencies Bring in libraries such as coroutines and serialization
Multi-module builds Build all modules of the entire project with one command Server + common library + test modules
Task orchestration Tasks have dependencies on each other and run automatically in order Package after compiling, run tests before packaging
Incremental builds Reprocess only the files that have changed Faster rebuilds for large projects
Multi-Language Support Mix Kotlin, Java, and resource files in the same project Gradually migrate legacy Java projects to Kotlin

Project directory structure

Gradle follows "convention over configuration": source code goes in fixed directories, with no need to declare paths explicitly.

Kotlin Gradle project directory structure: the root directory contains build.gradle.kts, settings.gradle.kts, gradle/wrapper, src/main/kotlin, and src/test/kotlin, along with a description of each one's purpose

A standard Kotlin/JVM project structure is shown below; source sets are divided into main and test.



runoob-demo/

├── build.gradle.kts          # 构建脚本,声明插件、依赖、任务

├── settings.gradle.kts       # 项目名与子模块声明

├── gradle.properties         # 可选,构建参数与 JVM 参数

├── gradlew                   # Linux/macOS 下的 Gradle Wrapper 脚本

├── gradlew.bat               # Windows 下的 Gradle Wrapper 脚本

├── gradle/wrapper/           # Wrapper 的 jar 与版本配置

└── src

    ├── main/kotlin/          # 主源码集,参与最终产物

    │   └── com/runoob/Main.kt

    └── test/kotlin/          # 测试源码集,不进入最终产物

        └── com/runoob/MainTest.kt

Kotlin source files use the .kt extension, and the package name com.runoob corresponds to the directory src/main/kotlin/com/runoob.

When you create a Kotlin project in IntelliJ IDEA, the IDE generates this structure automatically; you only need to focus on the src directory and the two build scripts.

Tip:Always use the project's own gradlew rather than the system-installed gradle command. gradlew locks the build tool version, ensuring consistent build results for every team member and every machine.


Minimal build.gradle.kts configuration

The build script is the heart of the project; the configuration below is already enough to compile, run, and test.

File path: build.gradle.kts.

Example

// File path: build.gradle.kts

plugins

{

   

// Kotlin/JVM plugin; 2.2.0 is the version baseline for this chapter

    kotlin

(

"jvm"

)

version

"2.2.0"

   

// The application plugin generates a run task so the project can be started directly

    application

}

group

=

"com.runoob"

   

// Organization identifier, affecting coordinates when publishing

version

=

"1.0.0"

     

// Project version

repositories

{

   

// Dependency repositories; mavenCentral is where the vast majority of open-source libraries live

    mavenCentral

(

)

}

dependencies

{

   

// Test dependencies, visible only in the test source set

    testImplementation

(

kotlin

(

"test"

)

)

}

kotlin

{

   

// Lock the JDK version used for compilation to avoid inconsistent results across machines

    jvmToolchain

(

17

)

}

application

{

   

// Full name of the main class; a Kotlin top-level main function compiles to a class name with a Kt suffix

    mainClass.

set

(

"com.runoob.MainKt"

)

}

The accompanying project name declaration is written in settings.gradle.kts, which Gradle executes first at startup.

Example

// File path: settings.gradle.kts

// Project name, affecting the default name of build artifacts

rootProject.

name

=

"runoob-demo"

The main program file goes in src/main/kotlin/com/runoob/Main.kt.

Example

// File path: src/main/kotlin/com/runoob/Main.kt

package

com.runoob

fun main

(

)

{

    println

(

"Hello, Runoob!"

)

    println

(

"Website: www.runoob.com"

)

}

Run the run task to see the output.



$ ./gradlew run



> Task :run

Hello, Runoob!

网站:www.runoob.com



BUILD SUCCESSFUL in 1s

The purpose of each configuration block in the script can be understood from the table below.

Configuration block Purpose Required
plugins Declares the Gradle plugins used, determining what capabilities the project has Required
group / version Project coordinates, used when publishing to a repository Optional
repositories Declares where dependencies are downloaded from Required when there are dependencies
dependencies Declares the third-party libraries the project depends on Optional
kotlin Extension configuration provided by the Kotlin plugin, such as JDK version and compiler arguments Optional
application Extension configuration of the application plugin, specifying the main class and startup arguments Required when using the application plugin

Dependency Management

The key to dependency configuration is not "which line to write" but understanding each configuration's visibility and transitivity rules.

The same dependency declared in different configurations yields completely different visible source sets and transitivity to downstream modules.

Configure Visible at compile time Visible at runtime Passed to downstream modules Typical scenario
implementation Is Is No Libraries used for internal implementation; recommended as the default
api Is Is Is Types exposed to callers in the public API
testImplementation Test source set only Test source set only No Test frameworks and assertion libraries
runtimeOnly No Is No Libraries loaded on demand, such as JDBC drivers and logging implementations

The difference between implementation and api only shows up in multi-module projects; in a single-module project they have the same effect.

A library brought in with implementation by one module is not visible to downstream modules at compile time, so upgrading or replacing it upstream will not break downstream code.

Only when downstream code must directly use a library's types should you expose it with api.

Example

// File path: build.gradle.kts

dependencies

{

   

// Used in main code: coroutines library

    implementation

(

"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2"

)

   

// Serialization types are exposed directly in the public API, so use api

    api

(

"org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0"

)

   

// Test only: JUnit 5

    testImplementation

(

"org.junit.jupiter:junit-jupiter:5.11.4"

)

   

// Needed only at runtime: MySQL driver; its classes do not appear in compile-time code

    runtimeOnly

(

"com.mysql:mysql-connector-j:9.1.0"

)

}

A dependency coordinate uses the three-part form "group:name:version"; the version must be written in full, otherwise Gradle cannot resolve it.

There is also a compileOnly configuration for libraries visible only at compile time and provided by the container at runtime, such as servlet-api.

Note:The compile configuration common in older materials was removed in Gradle 7.0; use implementation or api instead. Whenever you see compile, you should replace it.


Plugins and version management

Plugins determine what a project can do; the most core plugin for a Kotlin project is kotlin("jvm").

It provides Kotlin compilation tasks, standard library dependencies, and the kotlin extension configuration; its version must match your Kotlin version.

As a project grows and dependencies multiply, scattering version numbers across build.gradle.kts files becomes hard to maintain.

Gradle provides a Version Catalog, centralizing versions in gradle/libs.versions.toml.

Example

File path: gradle

/

libs.

versions

.

toml

[

versions

]

Manage versions centrally; change them here only when upgrading

kotlin

=

"2.2.0"

coroutines

=

"1.10.2"

junit

=

"5.11.4"

[

libraries

]

Dependency aliases, for use in build.

gradle

.

kts

via libs.

xxx

reference

coroutines

core

=

{

module

=

"org.jetbrains.kotlinx:kotlinx-coroutines-core"

, version.

ref

=

"coroutines"

}

junit

jupiter

=

{

module

=

"org.junit.jupiter:junit-jupiter"

, version.

ref

=

"junit"

}

[

plugins

]

Plugin aliases, referenced by the plugins block

kotlin

jvm

=

{

id

=

"org.jetbrains.kotlin.jvm"

, version.

ref

=

"kotlin"

}

With a Version Catalog, the build script can be written as shown below, with no hardcoded version numbers anywhere.

Example

// File path: build.gradle.kts

plugins

{

   

// Reference a plugin alias defined in the Version Catalog

    alias

(

libs.

plugins

.

kotlin

.

jvm

)

    application

}

repositories

{

    mavenCentral

(

)

}

dependencies

{

    implementation

(

libs.

coroutines

.

core

)

    testImplementation

(

libs.

junit

.

jupiter

)

}

application

{

    mainClass.

set

(

"com.runoob.MainKt"

)

}

There is a compatibility relationship between Kotlin plugin and Gradle versions; when upgrading, check the official compatibility table first and do not skip versions arbitrarily.


Common tasks and commands

All Gradle work is organized around tasks; a task name can be written directly after gradlew to execute it.

The following tasks cover the vast majority of day-to-day development scenarios.

Task Command Purpose
build ./gradlew build Compile main and test code, run tests, and package a jar
run ./gradlew run Run the main class specified by the application plugin
test ./gradlew test Run all tests; reports are under build/reports/tests
clean ./gradlew clean Delete the build directory, cleaning all build artifacts
compileKotlin ./gradlew compileKotlin Compile only the main source set, without running tests
jar ./gradlew jar Package only the jar, without running tests
tasks ./gradlew tasks List all executable tasks in the current project
dependencies ./gradlew dependencies Print the full dependency tree to troubleshoot version conflicts

Running the build task compiles, tests, and packages in sequence, and the output shows the execution status of each task.



$ ./gradlew build



> Task :compileKotlin

> Task :compileJava NO-SOURCE

> Task :processResources

> Task :classes

> Task :jar

> Task :compileTestKotlin

> Task :test

> Task :check

> Task :build



BUILD SUCCESSFUL in 3s

On Windows, just replace ./gradlew with gradlew.bat; all other arguments are exactly the same.

Tip:Task names support abbreviations; as long as the prefix is unique, ./gradlew cK is equivalent to ./gradlew compileKotlin. When unsure whether an abbreviation is unique, writing the full name is safer.


Multi-module projects in brief

As a project grows, putting all code in one module slows down builds and hinders reuse.

A multi-module project uses one root project to manage several submodules, each with its own build.gradle.kts.

First declare which modules to include in settings.gradle.kts.

Example

// File path: settings.gradle.kts

rootProject.

name

=

"runoob-multi"

// Declare submodules; a colon indicates directory hierarchy

include

(

":app"

)

   

// Executable module

include

(

":core"

)

   

// Common logic module

include

(

":data"

)

   

// Data access module

Submodules depend on each other via the project function; the colon-prefixed notation is Gradle's standard syntax.

Example

// File path: app/build.gradle.kts

plugins

{

    kotlin

(

"jvm"

)

version

"2.2.0"

    application

}

dependencies

{

   

// Depend on the core module in the same project

    implementation

(

project

(

":core"

)

)

    implementation

(

project

(

":data"

)

)

}

application

{

    mainClass.

set

(

"com.runoob.app.MainKt"

)

}

The root build.gradle.kts is usually used only to configure all submodules uniformly, such as unifying the JDK version and repository addresses.

Example

// File path: build.gradle.kts (root project)

// Uniform configuration for all subprojects

subprojects

{

    repositories

{

        mavenCentral

(

)

   

}

}

The directory structure of a multi-module project is similar to a single-module one, except each module has its own set of src directories.



runoob-multi/

├── settings.gradle.kts

├── build.gradle.kts

├── app/

│   ├── build.gradle.kts

│   └── src/main/kotlin/...

├── core/

│   ├── build.gradle.kts

│   └── src/main/kotlin/...

└── data/

    ├── build.gradle.kts

    └── src/main/kotlin/...


Comparison with Maven

Maven appeared earlier, with a mature ecosystem and a fixed configuration format; Gradle is more flexible and builds faster.

Both can build Kotlin projects; the choice depends on team habits and project needs.

Comparison Item Gradle Maven
Configuration file build.gradle.kts(Kotlin DSL) pom.xml(XML)
Programmable Yes; configuration is code No; declaration only
Build speed Incremental builds and build cache, usually faster Relatively slow
Dependency configuration implementation / api distinguish visibility compile / runtime / provided
Learning curve Steeper; requires understanding the task and configuration phases Gentler; fixed structure
Ecosystem and plugins Rich plugins; the top choice for Android Mature plugins; common in enterprise Java projects
Official recommendation Official default for Kotlin and Android Can be an alternative for Kotlin projects

If you maintain an existing Maven project, there is no need to switch build tools just to use Kotlin; kotlin-maven-plugin can compile Kotlin as well.

For new projects, it is recommended to use Gradle directly, especially when Android or multiplatform is involved.


Common questions

The following issues are the ones most often encountered when first using Gradle.

What is the difference between gradlew and gradle

gradlew is the project's bundled Wrapper script; it downloads and uses the Gradle version specified in gradle/wrapper/gradle-wrapper.properties.

gradle is the global command installed on your system, whose version may not match the project's requirement, so always prefer gradlew.

Dependency downloads are slow or fail

By default, dependencies are downloaded from Maven Central; networks in China may be slow, so you can switch to a mirror repository in repositories.

Example

// File path: build.gradle.kts

repositories

{

   

// Put the mirror repository first so downloads prefer the mirror

    maven

{

url

=

uri

(

"https://maven.aliyun.com/repository/public"

)

}

    mavenCentral

(

)

}

Compilation error saying the Kotlin standard library cannot be found

Check whether the plugins block declares the kotlin("jvm") plugin; the plugin automatically adds kotlin-stdlib as a dependency, so there is no need to write it manually.

JDK version mismatch

It is recommended to use kotlin { jvmToolchain(17) } to specify the JDK uniformly; Gradle will automatically find or download the corresponding version.

If you do not want Gradle to download a JDK, you can also install one locally and specify its path via org.gradle.java.installations.paths.