Gradle leftshift << operator with Task needed? (Is it superfluous)

The left shift (<<) operator is an alias to Task.doLast(), meaning that it adds an action to the task. A task action being some code that is evaluated when the task executes. Omitting the operator simply configures the task. The distinction being that one runs at configuration time (when Gradle runs your build script) and the other at execution time.

Essentially this example

task foo << { 
    println 'bar' 
}

is equivalent to

task foo {
    doLast {
        println 'bar'
    }
}

Mark Vieira's answer is exactly right, but I would also add for clarification, that without the << operator, the code in your closure will be executed when the script is parsed, rather than when it is executed.

This is most obvious when you run the "clean" task. If you don't use the << for all your tasks, then gradle clean will actually execute the code in all your tasks.

Try this:

build.gradle:

apply plugin: 'groovy'

task foo { println 'foo'}

and now try running the clean task

$>gradle clean
14:23:57: Executing external task 'clean'...
foo
:clean UP-TO-DATE

BUILD SUCCESSFUL

Total time: 0.216 secs
14:23:57: External task execution finished 'clean'.`

Now, if you add the <<,

build.gradle:

apply plugin: 'groovy'

task foo << { println 'foo'}

it will do this:

$>gradle clean
14:27:28: Executing external task 'clean'...
:clean UP-TO-DATE

BUILD SUCCESSFUL

Total time: 3.547 secs
14:27:32: External task execution finished 'clean'.

Note that the leftshift << operator was deprecated and is no longer in gradle versions 5.0 and up. You can replace the code above with:

build.gradle:

task foo { doLast { println 'foo' } }

Tags:

Gradle