Search

Dark theme | Light theme

November 15, 2016

Gradle Goodness: Replacing << Operator For Tasks

Gradle 3.2 deprecates the << operator to add actions to a task. The << operator maps to the leftShift method of a task. This operator confuses a lot people that are new to Gradle. Because without the operator we are configuring a task instead of adding actions. I can tell from experience the mistake is easily made. If we use the << in our build script with Gradle 3.2 we get a warning on the console. The warning message already mentions a solution: use the doLast method to add actions.

In the following example build script we define the task deprecatedSample using the << operator. The other task newSample uses the doLast method to add an action:

// Since Gradle 3.2 the << (leftShift) operator
// is deprecated. The operator can confuse
// people, because without the operator
// we would configure the deprecatedSample task,
// instead of adding the action statement:
// println 'Sample task'.
task deprecatedSample << {
    println 'Sample task'
}

// To have no confusion we should use
// the doLast method of a task to add
// the action statement:
// println 'Sample task'.
task newSample {
    doLast {
        println 'Sample task'
    }
}

When we run the deprecatedSample task we see in the output the warning that the leftShift method has been deprecated:

$ gradle deprecatedSample
The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
        at build_dq65b0mbv52w2ikhya3h9ru8d.run(/Users/mrhaki/Projects/mrhaki.com/blog/posts/samples/gradle/leftShift/build.gradle:7)
:deprecatedSample
Sample task

BUILD SUCCESSFUL

Total time: 0.793 secs
$

We still have time to fix our build scripts, because in Gradle 5 the leftShift method will be removed.

Written with Gradle 3.2.