Task inheritance?

This is probably more of a Groovy question than Gradle, per se, but I have a bunch of related tasks which look like so:

def showReport = { report ->
    java.awt.Desktop.desktop.browse file("$buildDir/$report").toURI()
}

task showJavadoc(group: 'Report', description: 'Opens the Javadoc in a browser.') << {
    showReport('docs/javadoc/index.html')
}

task showJunitReport(group: 'Report', description: 'Opens the JUnit report in a browser.') << {
    showReport('reports/tests/index.html')
}

...

I’ve factored out some of the redundancy, but I’m pretty sure Groovy is able to eliminate almost all of it. Any tips?

Basically, what you have are a bunch of tasks with the same behavior, but are configured differently (they open a different file). You’ll want to create a custom task for this.

task showJavaDoc(type: ShowReportTask) {
    dependsOn javadoc
    report 'docs/javadoc/index.html'
}

class ShowReportTask extends DefaultTask {
    Object report;

    @TaskAction
    showReport() {
        java.awt.Desktop.desktop.browse(project.file(report).toURI())
    }
}