Default value for a $PROPERTY in Gradle
18,762
Solution 1
if (!project.hasProperty("build_version")) {
ext.build_version = "1.0"
}
Solution 2
This checks if the property exists and assigns a default value if not:
def build_version=project.properties['build_version'] ?: "nokey"
Solution 3
This worked for me:
def AWS_ACCESS_KEY="nokey"
def AWS_SECRET_KEY="nokey"
if (project.hasProperty("AWS_ACCESS_KEY")) {
AWS_ACCESS_KEY=project.get("AWS_ACCESS_KEY")
}
if (project.hasProperty("AWS_SECRET_KEY")) {
AWS_SECRET_KEY=project.get("AWS_SECRET_KEY")
}
Solution 4
Another way to make it short and nice:
ext.buildVersion = project.getProperties().getOrDefault("build_version", "1.0")
Solution 5
Starting from Gradle 2.13:
ext.buildVersion = project.findProperty('build_version') ?: '1.0'
Author by
Zero Distraction
Updated on June 03, 2022Comments
-
Zero Distraction almost 2 years
How can I specify a default value for this simple
build.gradle
script:println "Hello $build_version"
So that I don't get the error:
A problem occurred evaluating root project 'hello_gradle'. > Could not find property '$build_version' on root project 'hello_gradle'.
I tried some of the operators, checking for nulls etc, but I think just the reference to the property makes it fail. I could fix that by always providing the property, but that's less than ideal.
gradle -Pbuild_version=World