I am aware of the difference between passing in a configuration closure and defining an action for a task. I believe you can't use <<
in a configuration closure because it seems like a syntax error:
task wrong {
<< { println "From doLast" }
}
But. Why can't I use leftShift
as an equivalent of <<
in the above configuration closure? In an even more clear test case, why doesn't the following buildfile output the line From leftShift - inside
?
defaultTasks 'tryout'
task tryout {
doLast { println "From doLast" }
leftShift { println "From leftShift - inside" }
}
tryout.leftShift { println "From leftShift - outside" }
Of course, this is not a real problem, as I can simply use doLast. I'm just trying to broaden my understanding of Gradle. Thanks!
The doLast creates a task action that runs when the task executes. Without it, you're running the code at configuration time on every build. Both of these print the line, but the first one only prints the line when the testTask is supposed to be executed.
Gradle supports two types of task. One such type is the simple task, where you define the task with an action closure. We have seen these in Build Script Basics. For this type of task, the action closure determines the behaviour of the task. This type of task is good for implementing one-off tasks in your build script.
Gradle has different phases, when it comes to working with the tasks. First of all, there is a configuration phase, where the code, which is specified directly in a task's closure, is executed. The configuration block is executed for every available task and not only, for those tasks, which are later actually executed.
You define a Gradle task inside the Gradle build script. You can define the task pretty much anywhere in the build script. A task definition consists of the keyword task and then the name of the task, like this: task myTask. This line defines a task named myTask .
<<
when used with a task definition, is not really a leftshift in the bitwise sense. It is shorthand for doLast
. In gradle DSL:
task hello << {
println 'Hello world!'
}
is exactly the same as:
task hello {
doLast{
println 'Hello world!'
}
}
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