Can anyone tell me why this code is working as expected:
tasks.register("startServer") {
doLast {
logger.lifecycle("Connecting to localhost:8090")
Socket("localhost", 8090).use {
println("Server is up and running on localhost:8090")
}
}
}
and this one is not:
val serverPort: Int = 8090
tasks.register("startServer") {
doLast {
logger.lifecycle("Connecting to localhost:${serverPort}")
Socket("localhost", serverPort).use {
println("Server is up and running on localhost:8090")
}
}
}
The piece with a variable serverPort never logs anything, even not the part in logger.lifecycle, but the piece without a variable works fine o.O.
Before I was able to go back to that my colleague found an answer with chatgpt:
In Kotlin DSL for Gradle, the lambda you pass to doLast is executed at a later time when the task actually runs, which is after the configuration phase. If the lambda captures references that depend on the build script’s instance (this), you may end up with context issues like the one you’re seeing. This can happen especially when the property is declared at the project level but used within task actions in a way that the context isn’t captured correctly.
So, the solution was to create another variable inside a task:
val serverPort: Int = 8090
tasks.register("startServer") {
val serverPort = serverPort // The name can even be the same
doLast {
logger.lifecycle("Connecting to localhost:${serverPort}")
Socket("localhost", serverPort).use {
println("Server is up and running on localhost:8090")
}
}
}
Is it stated somewhere in the docs? It’s pretty easy to stumble upon it and I couldn’t find any solution just by googling the problem.
It works just fine also without that extra variable.
As long as you do not use configuration cache that is.
If you do use configuration cache, it still works fine but then fails when trying to persist the CC entry.
There is not really any reason why it should not work from what you have shown.
I even copied it and tried it to make sure.
That’s why I asked for the build scans, to gather more information about what is happening.
Ah, yeah, that’s an important detail you left out.
With that I could have answered right away and it is one of the rare cases ChatGPT indeed gave a correct answer, even if slightly incomplete.
You use configuration cache on a Gradle version where it was not yet a stable feature iirc. Recent versions with stable CC will work but fail persisting the CC entry with an according entry in the CC report.