Kotlin
Gradle
Learn build configuration with Gradle.
Gradle: Build tool
Gradle is the build tool that manages dependencies, compilation and tests in Kotlin projects. Settings are written in the build.gradle.kts file using the Kotlin DSL. The file has plugins, dependencies and repositories blocks.
plugins {
kotlin("jvm")
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0")
}
Here the JVM plugin and the kotlinx.coroutines dependency are added. The repositories block states where dependencies are downloaded from (usually Maven Central). Gradle reads this file, downloads dependencies and compiles the project. From the command line ./gradlew build runs the whole build.
The build.gradle.kts structure
The build.gradle.kts file describes the structure of the project. At the top the plugins block lists plugins (for example kotlin("jvm")). Then repositories specifies dependency sources, and dependencies lists the libraries used. implementation means the dependency is used at compile time and runtime.
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("test"))
}
Here the Maven Central repository and the Kotlin test library are added. Besides implementation there are testImplementation (only in tests) and api (exposed to users of this module). Choosing the right scope affects build time and visibility.
Exercise Write a buildFile function
Define fun buildFile(): String. Its body returns "plugins { kotlin(\"jvm\") }\ndependencies { implementation(\"kotlinx-coroutines-core\") }" (use \n to separate two lines inside the string). In main print the output with println(buildFile()).
Show example solution
fun buildFile(): String {
return "plugins { kotlin(\"jvm\") }\ndependencies { implementation(\"kotlinx-coroutines-core\") }"
}
fun main() {
println(buildFile())
}
Test yourself
-
Match the Gradle blocks
- plugins
- Plugins
- dependencies
- Libraries
- repositories
- Download sources
- build.gradle.kts
- Build file
-
The dependency block
____ {
implementation("kotlinx-coroutines-core")
}
Show answer
dependencies {
implementation("kotlinx-coroutines-core")
}
-
In build.gradle.kts, where do you add libraries?
- The plugins block
- The dependencies block
- The tasks block
- The repositories block
Show answer
The dependencies block — The dependencies block adds libraries with implementation.
Next lesson: kotlinx