How to conditionally accept Gradle build scan plugin terms of service in Kotlin DSL?

The Gradle Kotlin DSL provides a withGroovyBuilder {} utility extension that attaches the Groovy metaprogramming semantics to any object. See the official documentation.

extensions.findByName("buildScan")?.withGroovyBuilder {
  setProperty("termsOfServiceUrl", "https://gradle.com/terms-of-service")
  setProperty("termsOfServiceAgree", "yes")
}

This ends up doing reflection, just like Groovy, but it keeps the script a bit more tidy.


It's not exactly nice, but using reflection it works:

if (hasProperty("buildScan")) {
    extensions.configure("buildScan") {
        val setTermsOfServiceUrl = javaClass.getMethod("setTermsOfServiceUrl", String::class.java)
        setTermsOfServiceUrl.invoke(this, "https://gradle.com/terms-of-service")

        val setTermsOfServiceAgree = javaClass.getMethod("setTermsOfServiceAgree", String::class.java)
        setTermsOfServiceAgree.invoke(this, "yes")
    }
}