What's the difference between the following two code snippets?
First:
task copyFiles(type: Copy) << {
from "folder/from"
into "dest/folder"
}
Second:
task copyFiles(type: Copy) {
from "folder/from"
into "dest/folder"
}
The work that Gradle can do on a project is defined by one or more tasks. A task represents some atomic piece of work which a build performs. This might be compiling some classes, creating a JAR, generating Javadoc, or publishing some archives to a repository.
In Gradle, Task is a single unit of work that a build performs. These tasks can be compiling classes, creating a JAR, Generating Javadoc, and publishing some archives to a repository and more. It can be considered as a single atomic piece of work for a build process.
The difference I see between a task and a method is that I can pass parameter/argument when calling a method and also return values from a method. I can't do that with task. And, when I need to run the build script, I can't call any method. I can only do that via a task.
In short, the first snippet is getting it wrong, and the second one is getting it right.
A Gradle build proceeds in three phases: initialization, configuration, and execution. Methods like from
and into
configure a task, hence they need to be invoked in the configuration phase. However, <<
(which is a shortcut for doLast
) adds a task action - it instructs the task what to do if and when it gets executed. In other words, the first snippet configures the task in the execution phase, and even worse, after its main (copy) action has been executed. Hence the configuration won't have any effect.
Typically, a task has either a type (which already brings along a task action) or a <<
(for an ad-hoc task). There are legitimate uses cases for having both (doing a bit of custom work after the task's "main" work), but more often that not, it's a mistake where the task gets configured too late.
I generally recommend to use doLast
instead of <<
, because it's less cryptic and makes it easier to spot such mistakes. (Once you understand the concepts, it's kind of obvious that task copyFiles(type: Copy) { doLast { from ... } }
is wrong.)
The first block of code create a task and append an Action to it. A task is composed of actions which are instructions blocks run sequentially when the task is called
The second block create a task and configure it. These instructions are run in the gradle "configuration" lifecycle phase.
here you find a clear explanation of the differences
here you can find an in depth explanation of gradle tasks
here is the gradle guide about lifecycle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With