Gradle Kotlin script: apply(from=) failed (not the same context)

Hi

We are currently updating our Groovy build script to Kotlin (.gradle.kts).

We have the following structure, to avoid duplicating some configuration:

in app/build.gradle:

...
apply from "${rootProject.rootDir}/settings/lint.xml"
apply from "${rootProject.rootDir}/settings/detekt.xml"
...
android {
 ...
}

And for example in settings/lint.xml:

android {
    lintOptions {
        checkDependencies true
        textReport true
        htmlReport true
        sarifReport true
       ...
    }
}

Same thing for detekt and other plugins.

When trying to do convert theses file to kotlin (dsl?) it didn’t work.
For the lint file, the “android” plugin do not exists in the scope, I got the messages:

* Where:
Script '/home/user/src/android-project/settings/lint.gradle.kts' line: 2

* What went wrong:
Script compilation errors:

  Line 02: android {
           ^ Unresolved reference: android

  Line 03:     lintOptions {
               ^ Unresolved reference: lintOptions

  Line 04:         checkDependencies = true
                   ^ Unresolved reference: checkDependencies

I tried many things, like:

  • moving theses script to buildSrc (and use plugins {id("lint-config")} in app/build.gradle.kts),
  • Extends the plugins (!!!)
    but with no luck.

Any idea ?
Thanks !

Using a precompiled script plugin, for example in buildSrc or - what I prefer - in an included build is exactly the way to go.
Normal script plugins are very limited, especially when it comes to Kotlin DSL as you for example cannot apply plugins using plugins { ... } DSL, can easily get into classloader problems, and do not get type-safe accessors generated like android { ... }.

But even in precompiled script plugins, only the accessors for plugins that are applied in the same script using the plugins { ... } block are generated.

So you either have to apply the plugins you want to configure within that same precompiled script plugin, or you have to use the more verbose syntax like

configure<AndroidExtensionOrHoweverTheClassIsCalled> {
    ...
}

You might also find this helpful: Migrating build logic from Groovy to Kotlin

Thank you for the reply.
I’ll try that today.