← Back to Kotlin Course | Chapter 14: JVM Interop & Best Practices | Lesson 3 of 7

Gradle Basics

Gradle is the assistant that downloads the pieces your Kotlin project needs and knows how to build and run it with a single command.

What Gradle Does

Gradle automates compiling source code, running tests, resolving dependencies, and packaging a finished application, replacing manual kotlinc invocations for anything beyond a tiny project.

Example: What Gradle Does

markup
fun main() {
    println("In a real project, Gradle would compile and run this instead of calling kotlinc directly")
}

The build.gradle.kts File

A Kotlin project's build configuration -- plugins, dependencies, and settings -- is typically declared in build.gradle.kts, using Kotlin syntax itself.

Example: The build.gradle.kts File

bash
plugins {
    kotlin("jvm") version "1.9.22"
    application
}

dependencies {
    implementation(kotlin("stdlib"))
}

application {
    mainClass.set("MainKt")
}

⚠️ Run this command in your terminal.

Adding Dependencies

Third-party libraries, such as kotlinx-coroutines-core, are declared inside a dependencies { } block with an implementation scope and version, and Gradle downloads them automatically.

Example: Adding Dependencies

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

⚠️ Run this command in your terminal.

Common Gradle Commands

./gradlew build compiles and tests the project, ./gradlew run executes the application's main class, and ./gradlew test runs just the test suite -- the gradlew wrapper script means nobody needs Gradle installed separately.

Example: Common Gradle Commands

bash
./gradlew build
./gradlew run
./gradlew test

⚠️ Run this command in your terminal.

Common Mistakes
  1. Editing the wrong build file section (like dependencies vs plugins) and being confused why a new library isn't recognized.
  2. Forgetting to run ./gradlew build (or an IDE sync) after changing build.gradle.kts, so the new configuration never takes effect.
  3. Mixing Groovy (build.gradle) and Kotlin DSL (build.gradle.kts) syntax in the same file by copying snippets from the wrong source.
Chapter Summary
  • Gradle is a build automation tool that compiles, tests, and packages Kotlin (and other JVM) projects.
  • build.gradle.kts (Kotlin DSL) or build.gradle (Groovy DSL) declares a project's plugins, dependencies, and build configuration.
  • ./gradlew build compiles the project, runs tests, and produces build artifacts using a wrapper that doesn't require Gradle to be separately installed.
  • Dependencies are added under a dependencies { } block, specifying the library and version needed.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.