Shared variables in Gradle's buildscript block

‹ adb force install | Robolectric in gradle ›

Gradle documentation on the internet has numerous examples of global variables that are defined at the top level of the file like this:

androidPluginVersion = '0.8.+'
buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "com.android.tools.build:gradle:$androidPluginVersion"
  }
}

Defining data in variables like this can be useful in the case of multi-project builds, but the above build.gradle actually causes an error:

> No such property: androidPluginVersion for class: org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler

because the buildscript block is evaluated first, before androidPluginVersion has been defined. Instead, the variable definition must go in the buildscript block like this:

buildscript {
   ext {
     androidPluginVersion = '0.8.+'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath "com.android.tools.build:gradle:$androidPluginVersion"
   }
}

This will define androidPluginVersion both inside and outside the buildscript scope.

Comments

Thank you very much for this tip! I was almost giving up on being able to define properties across buildscript boundaries.

Alternatively, if you want to have only variables at the top:

buildscript {

ext {

myVar = "value"

}

Then open another buildscript block later in the code (wherever) and it will know about myVar. I usually put all my "ext" at the top of the build gradle file.

Subscribe to All Posts - Wesley Tanaka