Gradle Basics
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
fun main() {
println("In a real project, Gradle would compile and run this instead of calling kotlinc directly")
}
Login to try C/C++/Java/PHP code in the editor
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
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
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
./gradlew build
./gradlew run
./gradlew test
⚠️ Run this command in your terminal.
- Editing the wrong build file section (like
dependenciesvsplugins) and being confused why a new library isn't recognized. - Forgetting to run
./gradlew build(or an IDE sync) after changingbuild.gradle.kts, so the new configuration never takes effect. - Mixing Groovy (
build.gradle) and Kotlin DSL (build.gradle.kts) syntax in the same file by copying snippets from the wrong source.
- Gradle is a build automation tool that compiles, tests, and packages Kotlin (and other JVM) projects.
build.gradle.kts(Kotlin DSL) orbuild.gradle(Groovy DSL) declares a project's plugins, dependencies, and build configuration../gradlew buildcompiles 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: