Default value for a $PROPERTY in Gradle

Viewed 20451

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
8 Answers

Starting from Gradle 2.13:

ext.buildVersion = project.findProperty('build_version') ?: '1.0'

Another way to make it short and nice:

ext.buildVersion = project.getProperties().getOrDefault("build_version", "1.0")

I'm adding this to my build.gradle:

String propValue(String propName, String defValue) {
    (project.hasProperty(propName) && project.getProperty(propName)) ? project.getProperty(propName) : defValue
}

then use when needed propValue('build_version', 'nokey').

Have you tried this?:

println "Hello ${project.getProperty('build_version', 'default_string_value')}"

One-liner using ternary operator:

println "Hello ${project.hasProperty('build_version') ? getProperty('build_version') : 'World'}"

gradle <your_task> -Pbuild_version=SomethingElse

Related