Search code examples
kotlingradle

Understanding Gradle's Kotlin DSL in terms of "plain Kotlin"


tldr: I don't see how Gradle's Kotlin DSL for defining tasks is valid Kotlin and I need references to official Kotlin docs that can explain it

The longer version

I am reading the docs of OpenAPI's Gradle Generator to try and understand the API and came across this bit in the docs:

// Define a task for validating one specification
task validateGoodSpec(type: org.openapitools.generator.gradle.plugin.tasks.ValidateTask) {
    inputSpec.set("$rootDir/petstore-v3.0.yaml")
}

Beside the point that this does not like how you register tasks in the official Gradle docs, this almost looks like a normal function definition (if one replaced task with `fun), but I do not remember coming across syntax like this in any "normal" Kotlin code. I know this is the Gradle DSL, but I still thought it was supposed to be valid Kotlin. Is this assumption wrong?

Stuffing the example into IntelliJ, it could not resolve this code to the right overloaded signature of the task function, which was a bit strange ...: failing explanation from intellij

I then tried asking ChatGPT to "translate" the Kotlin code to plain Java ... I think it was hallucinating, as it added an extra Class<T> argument out of nowhere, but after some cleanup, I think the result should be something like this

task<ValidateTask>("validateGoodSpec") {
    outputs.upToDateWhen {
        false;
    }
    // etc ....
}

This, at least, is code I understand how works and fits an existing function signature:

public open fun task(name: kotlin.String, configureAction: org.gradle.api.Action<in org.gradle.api.Task>): org.gradle.api.Task`

Still, the I have no idea how the Kotlin compiler magically can turn task validateGoodSpec(someAction) into task("validateGoodSpec", someAction)!


Solution

  • As comments already pointed out, the code you're showing isn't Kotlin DSL, it's Gradle's Groovy DSL. So, yes, this syntax is not valid Kotlin, and there is no real mystery :)

    That being said, there are weird things going on even in Kotlin DSL sometimes. The Kotlin code of Gradle build scripts is compiled with some twists. For instance, the property assignment syntax using = instead of .set(...) in Gradle 8.2 relies on a compiler plugin (see their blog post). So watch out for those!