CodeBlanks Logo Icon CodeBlanks

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.

Practice 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()).

Starter code

Main.kt
// buildFile function: return a string containing plugins and dependencies blocks
// main: print buildFile() with println
fun main() {
    // write here
}

Sample solution

Main.kt
fun buildFile(): String {
    return "plugins { kotlin(\"jvm\") }\ndependencies { implementation(\"kotlinx-coroutines-core\") }"
}

fun main() {
    println(buildFile())
}

Expected output

plugins { kotlin("jvm") }
dependencies { implementation("kotlinx-coroutines-core") }

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the Gradle blocks

Term Meaning
plugins Plugins
dependencies Libraries
repositories Download sources
build.gradle.kts Build file

2 The dependency block

Question
____ {
    implementation("kotlinx-coroutines-core")
}
Answer
dependencies {
    implementation("kotlinx-coroutines-core")
}

Explanation: The dependencies block lists libraries.

3 In build.gradle.kts, where do you add libraries?

  • The plugins block
  • The dependencies block Correct answer
  • The tasks block
  • The repositories block

Explanation: The dependencies block adds libraries with implementation.

All lessons in Intermediate