Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the operator << (double less than) in gradle?

Tags:

gradle

groovy

The following piece of code defines 4 gradle tasks:

4.times { counter ->
    task "task$counter" << {
        println "I'm task number $counter"
    }
}

But what is the << operator? What does it do in groovy?

like image 939
St.Antario Avatar asked Sep 28 '14 13:09

St.Antario


2 Answers

The << is a left-shift operator. In this scenario, task "task$counter" is a Task object declaration, and << is overloaded as an alias to the doLast method, which appends the closure to the list of actions to perform when executing the task.

If you don't specify the <<, the closure is treated as a configuration closure and will be executed by default during the configuration phase of your project's build lifecycle, regardless of whatever task argument is given on the command line.

Example:

If you take the configuration specified in the question:

4.times { counter ->
    task "task$counter" << {
        println "I'm task number $counter"
    }
}

And run gradle task3, the output will be:

:task3
I'm task number 3

Because each closure was defined to be an execution action specific to the task. Since task3 was named as the task to execute, that was the only action closure executed.

But if you remove the << and make the configuration as follows:

4.times { counter ->
    task "task$counter" {
        println "I'm task number $counter"
    }
}

And run gradle task3, the output will then be:

I'm task number 0
I'm task number 1
I'm task number 2
I'm task number 3
:task3 UP-TO-DATE

This is because all closures were defined to configure the tasks themselves, not be executed as actions when running the tasks. So in this case, Gradle executed all of the closures while configuring the project, then when it came time to execute task3, there were no actions to perform, so it reported the task as UP-TO-DATE.

like image 176
heenenee Avatar answered Nov 18 '22 01:11

heenenee


Basically this is a leftShift operator - You can find more details here.

In gradle << operator is used to add action to a particular task. A task consists of multiple actions that are run (in order they were added) during the execution of the task. << just adds an action to tasks collection of actions. More about tasks and actions can be found here.

like image 41
Opal Avatar answered Nov 17 '22 23:11

Opal