How to resolve properties that do not exist to null

Say I have a property that is optional and I want to resolve it to null if it does not exist

// Alternative 1: Using
def resolved =
    // Alternative 2: if-checking
def resolved = null
if (hasProperty('somePropertyName') {
   resolved = project.ext.somePropertyName

Is alternative 1 a viable option in this case?

1 Like

In most cases, yes. In fact, alternative 2 is not strictly correct either. The ‘Project.hasProperty()’ method will return true for many other values other than those available from the ‘ExtraPropertiesExtension’. See here for more information.

If the property you are interested in is a “user” property. Which means it is in a file, passed via the command line, or set as an “extra” property, then yes, alternative 1 will work fine.

1 Like