Search code examples
gradlebuild.gradlegradle-plugingradle-task

Gradle optional @Input


How can I provide an optional property for task?

class CustomTask extends DefaultTask {

    @Input
    Closure preconfig

    // ...    
}

This way obligates user to provide preconfig closure as parameter when defining task with CustomTask type.

How can I achieve declarative way other than defining methods to set properties?

class CustomTask extends DefaultTask {

    @Input
    Closure preconfig

    def preconfig(Closure c){
        this.preconfig = c
    }

    // ...   
}

Solution

  • Actually, I found a solution in assigning default value to the @Input fields.

    Example:

    class CustomTask extends DefaultTask {
    
        @Input
        Closure preconfig = null // or { } <- empty closure
    
        // ...    
    }
    

    And then check if the @Input variable is not null:

    // ...
    
    @TaskAction
    def action(){
        if (preconfig) { preconfig() }
    }
    
    // ...
    

    Also there is useful annotation @Optional:

    class CustomTask extends DefaultTask {
    
        @Input @Optional
        Closure preconfig
    
        // ...    
    }