Gradle - Get the default value (convention) of a Property

914 Views Asked by At

I want to achieve a very basic thing (in any normal language): I would like to get the default value (convention) of a Property. Gradle docs in chapter Lazy configuration, describes how to apply the convention to a Property:

def property = objects.property(String)

// Set a convention
property.convention("convention 1")
println("value = " + property.get())

// Can replace the convention
property.convention("convention 2")
println("value = " + property.get())

property.set("value")

// Once a value is set, the convention is ignored
property.convention("ignored convention")
println("value = " + property.get())

The problem is, that you cannot query the property to get information what is the convention (the default value) when you set a value. It seems that the only way it's to clear (nullify) the value:

property.value(null).get()

But this is just stupid because you are doing unnecessary actions, while the convention is somewhere there?

Does anyone know how to get it without clearing the value?

2

There are 2 best solutions below

0
On BEST ANSWER

The answer (for 2022) is: No, you can't get the default value (convention) of a Property.

2
On

I'll try to answer why set overrides the convention once it's called. The convention is the default value, once the property has a value by calling set the convention is ignored because the property has a value. That makes sense because that's what a default value should mean. If I have a value use that otherwise use this default value. Convention and set seem to follow that pattern. I don't quite follow why this is surprising to how you want to use gradle, but just as an outside observer I think gradle is doing what is expected.

You can test if a property exists using

if( property.isPresent() ) {
    // do whatever
}

I bet that isPresent() is going to say false when the convention would be returned by get(), but if you call set then isPresent() is going to return true.

Then there are other methods to help like:

def val = property.getOrElse( "SomeDefault" )
def maybe = property.getOrNull()

I do think Gradle doesn't always do a good job of making the API very accessible from their home page and docs (ie groovydoc) for answering more complex questions: https://docs.gradle.org/current/javadoc/org/gradle/api/provider/Property.html

These methods are the super interface Provider and hence why it may not be obvious they are available if you don't look up the chain:

https://docs.gradle.org/current/javadoc/org/gradle/api/provider/Provider.html