Gradle — Cheat Sheet

Tags: gradle, build-tool, java, kotlin, groovy, ci-cd, android, dependencies

Level: intermediate

TL;DR: A flexible and highly performant open-source build automation tool for the JVM ecosystem, utilizing a Groovy or Kotlin DSL instead of XML.

Key concepts

Uses a Directed Acyclic Graph (DAG) to determine the exact order of task execution.

Build phases: Initialization (sets up environment), Configuration (evaluates build scripts), Execution (runs required tasks).

Gradle Wrapper (gradlew): Scripts and a small JAR that automatically download the declared Gradle version to ensure consistent builds across machines.

Incremental builds: Gradle checks if inputs or outputs have changed and skips tasks that are already up-to-date.

Build cache: Reuses task outputs locally or across the network to drastically reduce build times.

Dependency scopes: implementation hides internal dependencies, while api exposes them to consumers.

Supports multi-project builds to manage large codebases composed of smaller, interdependent modules.

Typical questions and ready answers

Q: What is the difference between Gradle and Maven?R: Maven uses a rigid XML configuration with a fixed lifecycle. Gradle uses a Groovy or Kotlin DSL, offering much higher flexibility, better performance via incremental builds, and advanced caching.

Q: Why should we use the Gradle Wrapper?R: It guarantees that everyone on the team and the CI server uses the exact same Gradle version without requiring manual global installation.

Q: What is the difference between api and implementation dependencies?R: implementation restricts the dependency to the internal module, improving compilation time. api leaks the transitive dependency to modules that consume it.

Pitfalls and common mistakes

Executing heavy logic or network calls directly in the configuration phase rather than inside a task action (execution phase).

Using api everywhere instead of implementation, causing massive unnecessary recompilations across the project.

Forgetting to define inputs and outputs for custom tasks, which completely breaks Gradle's incremental build feature.

Snippets and commands

# Run a build using the wrapper
./gradlew build

# Clean the project
./gradlew clean

# See all available tasks
./gradlew tasks

# See dependency tree for a specific configuration
./gradlew dependencies --configuration compileClasspath

Kotlin

// Basic build.gradle.kts setup
plugins {
    kotlin("jvm") version "1.9.0"
    application
}

repositories {
    mavenCentral()
}

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

To review

[ ] Writing custom plugins (binary vs script plugins).

[ ] Advanced configuration cache troubleshooting.

[ ] Gradle build lifecycle hooks.

References

Official Gradle Documentation

Kotlin DSL Primer

Jarvis Interviews
Jarvis