Search code examples
gradlekotlingradle-kotlin-dsl

What is the difference between registering and creating in Gradle Kotlin DSL


There are two methods of creating, i.e. tasks, in Gradle (5.0+):

tasks {
    val javadocJar by creating(Jar::class) {
        val javadoc by tasks

        from(javadoc)
        classifier = "javadoc"
    }
}

and

tasks {
    val javadocJar by registering(Jar::class) {
        val javadoc by tasks

        from(javadoc)
        classifier = "javadoc"
    }
}

Basically the same API, so what's the difference?


Solution

  • See using the container API:

    tasks.named("check")
    tasks.register("myTask1")
    tasks.named<JavaCompile>("compileJava")
    tasks.register<Copy>("myCopy1")
    

    The above sample relies on the configuration avoidance APIs. If you need or want to eagerly configure or register container elements, simply replace named() with getByName() and register() with create().

    Difference between creating and registering (or create and register in Gradle versions prior to 5.0) is related to Task Configuration Avoidance new API, which is explained in details here (see this section):

    How do I defer task creation?

    Effective task configuration avoidance requires build authors to change instances of TaskContainer.create(java.lang.String) to TaskContainer.register(java.lang.String).

    …. The create(…​) API eagerly creates and configures tasks when it is called and should be avoided.

    Using register(…​) alone may not be enough to avoid all task configuration completely. You may need to change other code that configures tasks by name or by type, as explained in the following sections.

    EDIT: Also note that using withType<T> { } will immediately create and configure the task, and must be avoided using withType<T>().configureEach {} instead (source).

    How do I defer task configuration?

    Eager APIs like DomainObjectCollection.all(org.gradle.api.Action) and DomainObjectCollection.withType(java.lang.Class, org.gradle.api.Action) will immediately create and configure any registered tasks. To defer task configuration, you will need to migrate to a configuration avoidance API equivalent. See the table below to identify the alternative.