Sometimes I see:
task hey << {
println "Hello, Gradle!"
}
Other times I see:
task hey {
println "Hello, Gradle!"
}
When do use "<<
" and when do you not (and why)?
Sometimes I see:
task hey << {
println "Hello, Gradle!"
}
Other times I see:
task hey {
println "Hello, Gradle!"
}
When do use "<<
" and when do you not (and why)?
<<
is shorthand for doLast
. The tasks in your question are not equivalent.
This task:
task hey << {
println "Hello, Gradle!"
}
is equivalent to this task:
task hey {
doLast {
println "Hello, Gradle!"
}
}
The code in your second example will execute every time the build script executes, regardless of whether or not you are running that specific task. For example, if you had the following tasks and then ran gradle goodbye
, you would see both "Hello, World!" and "Goodbye, World!" even though you are only executing the "goodbye" task:
task hello {
println "Hello, world!"
}
task goodbye {
println "Goodbye, world!"
}
Results:
$ gradle goodbye
Hello, world!
Goodbye, world!
:goodbye UP-TO-DATE
However, if you updated the task definitions to use <<
or doLast
(e.g. task hello << {}
), you would only see the println
from the task you executed.
Adam Murdoch describes when the code in a task will be executed in this post. I've quoted some of the relevant information here:
There are 2 different points in time when code related to a task is executed: The first is configuration time, which is when the build script executes. The idea is that at this time you configure the task, so that it does the right thing at the other point in time, namely, execution time. Execution time is the point in time where the task does its actual work, and happens only if the task is selected for execution, and after its dependencies have executed.
Each task has a sequence of actions, which are run in the order specified when the task executes. An action is simply a closure or an Action implementation. The doFirst() method configures the task to add an action at the start of the sequence. The doLast() and << methods configure the task to add an action at the end of the sequence.
From the Gradle documentation:
This:
task hello {
doLast {
println 'Hello world!'
}
}
can be written as this:
task hello << {
println 'Hello world!'
}
Combining statements from the doc (near example 6.10):
The << operator is simply an alias for doLast (which adds an action to the the end of the task's actions list)
The time you might prefer to use the doLast
notation is if you want to combine task definition with task configuration. So instead of doing them separately as:
task helloCopy << {
println "hello"
}
task(helloCopy, type: Copy) {
from(file('srcDir'))
into(buildDir)
}
... you could instead do the following if you wish:
task(helloCopy, type: Copy) {
from(file('srcDir'))
into(buildDir)
doLast {
println "hello"
}
}
Whether or not you prefer that style is personal preference, but it keeps all specifications for a task together.