Avoiding common pitfalls

A common mistake when creating a task and adding actions for that task is that we forget the left shift operator (<<). Then we are left with a valid syntax in our build script, so we don't get an error when we execute the task. But instead of adding actions, we have configured our task. The closure we use is then interpreted as a configuration closure. All methods and properties in the closure are applied to the task. We can add actions for our tasks in the configuration closure, but we must use the doFirst and doLast methods. We cannot use the left shift operator (<<).

The following tasks do the same thing, but note the small subtle differences when we define the tasks:

def printTaskName = { task ->
    println "Running ${task.name}"
}

task 'one' {
    // Invoke doFirst method to add action.
    doFirst printTaskName
}

// assign action through left-shift operator (<<)
task 'two' << printTaskName

task 'three' {
    // This line will be displayed during configuration
    // and not when we execute the task, 
    // because we use the configuration closure
    // and forgot the << operator.
    println "Running three"
}

defaultTasks 'one', 'two'
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.172.38