Variables Outside of Blocks

Purpose:

Variables defined outside of any blocks in a Gradle build script are evaluated during the Configuration phase of the build lifecycle. This means they are initialized immediately, regardless of whether they are used in the final execution. This type of configuration is known as eager configuration.

Key Idea:

When variables are defined outside of Gradle blocks like plugins {}, repositories {}, or tasks {}, they are executed as part of the Configuration phase. These variables are initialized even if they are not used, which can affect performance by eagerly evaluating parts of the script that might not be needed.

Example:

println("DEFINING some variable in the build script outside of blocks, should happen as part of Configuration phase.")
val someVariable = "some value"

plugins {
    // Apply the org.jetbrains.kotlin.jvm Plugin to add support for Kotlin.
    alias(libs.plugins.kotlin.jvm)

    // Apply the java-library plugin for API and implementation separation.
    `java-library`
}

In the example above:

  • The println statement and the someVariable assignment are both executed immediately as part of the configuration phase.
  • Even though these statements are outside the plugins {} block, they are still eagerly executed when Gradle configures the build.

Use Case:

Eager configuration can be useful for setting up variables that are required during the build configuration. However, to improve performance, consider using lazy initialization (by lazy in Kotlin) or registering tasks lazily (tasks.register instead of tasks.create) to defer execution until necessary.

Glass thought Sandbox Snapshot

Command to reproduce:

gt.sandbox.checkout.commit 1fe9385f332d07cf842d \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew lazyTask"

Recorded output of command:


> Configure project :lib
DEFINING some variable in the build script outside of blocks, should happen as part of Configuration phase.
Eager task: configuration
Lazy task: configuration

> Task :lib:lazyTask
Lazy task

BUILD SUCCESSFUL in 376ms
1 actionable task: 1 executed