What is doLast() for?

Can someone explain what the doLast() method is for? All the examples for writing tasks in the manual show it being used. However, it appears to be totally extraneous, both of these do the same thing:

With doLast():

task("testTask") {
    doLast {
            println "hello testTask"
    }
}

Without:

task("testTask") {
            println "hello testTask"
}

So what is the point of doLast()?

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. The second one runs it when the build is configured, even if the task should not run.

3 Likes

Ahh ok, that makes sense:

task("testTask") {
println "before doLast()"
doFirst {
	println "hello doFirst"
}

doLast {
	println "hello doLast"
}

println "after doLast()"
}

Output:

./gradlew testTask


> Configure project :
before doLast()
after doLast()

> Task :testTask
hello doFirst
hello doLast

The manual should probably make this more clear.

I’m pretty sure the manual goes through specific examples just like that, and also references the Gradle Lifecycle. Is there a specific spot in the manual that you feel this should be mentioned, perhaps?

After posting this I actually did find it in the manual and the example in the manual actually looked a lot like mine. However, now since I am looking for it again I can’t find it, I thought I found it here https://docs.gradle.org/current/userguide/more_about_tasks.html but I don’t see it there now (I might just be skimming past it).

Ok, I found it, it is in the Build Lifecycle documentation: https://docs.gradle.org/current/userguide/build_lifecycle.html#sec:settings_file

This would probably be good info to have in the https://docs.gradle.org/current/userguide/more_about_tasks.html doc too

1 Like