Using variables in Gradle build script

If you're developing an Android APP using Gradle, you can declare a variable (i.e holding a dependency version) thanks to the keyword def like below:

def version = '1.2'
    
dependencies {
  compile "groupId:artifactId:${version}"
}

Hope that helped!


On android there are actually 2 possibilities how to achieve this. It really depends which suits your needs. Those two possibilities have their pros and cons. You can use def variable or ext{} block. Variable def is awesome because it lets you click on the variable and points exactly where it is defined in the file compared to ext{} block which does NOT points to that exact variable. On the other hand ext{} has one good advantage and that is you can refer variables from project_name/build.gradle to project_name/app/build.gradle which in some cases is very useful BUT as I said if you click on that variable lets say only inside only one file it wont points out to the definition of that variable which is very bad because it takes you more search time if your dependency list grows.

1) def option which is propably best and saves you search time.

def lifecycle = '2.0.0'

dependencies {
    implementation 'androidx.lifecycle:lifecycle-extensions:$lifecycle'
}

2) second ext{} block. Its kinda ok if dependency list is not huge.

ext {
    lifecycle = '1.1.1'
}

dependencies {
    implementation 'androidx.lifecycle:lifecycle-extensions:$lifecycle'
}

3) In some cases if you want to share variables between project_name/build.gradle and project_name/app/build.gradle use ext{}

in project_name/build.gradle you define kotlin_shared_variable:

buildscript {
    ext.kotlin_shared_variable = '1.3.41'

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_shared_variable"
    }
}

which you can use in project_name/app/build.gradle

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_shared_variable"
}

and of course you can combine them.


I think the problem may lay on string literal delimiters:

  1. The string literals are defined exactly as in groovy so enclose it in single or double quotes (e.g. "3.0.6.RELEASE");
  2. Gstrings are not parsed in single quotes strings (both single '...' or triple '''...''' ones) if i recall correctly;

So the code will be:

springVersion = '3.0.6.RELEASE' //or with double quotes "..."

task extraStuff{
    doStuff "org.springframework:spring-web:${springVersion}@war"
}

Tags:

Groovy

Gradle