Moving gradle kts functions to a separate file

Issue

Previously with Groovy, you could easily move parts of your build.gradle to separate files. But now using the Kotlin DSL I get unresolved references and I can’t seem to figure out why.

If I have this in my app/build.gradle.kts file, everything compiles nicely.

/**
 * Apply shared configurations to the android modules.
 */
fun com.android.build.gradle.BaseExtension.baseConfig() {
    plugins.withType<com.android.build.gradle.api.AndroidBasePlugin> {
        configure<com.android.build.gradle.BaseExtension> {
            defaultConfig {
                compileOptions {

                    compileSdkVersion(33)
                    defaultConfig {
                        minSdk = 23
                        targetSdk = 33
                    }

                    sourceCompatibility = JavaVersion.VERSION_11
                    targetCompatibility = JavaVersion.VERSION_11
                }
            }
        }
    }

    tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile> {
        kotlinOptions.jvmTarget = "11"
    }
}

/**
 * Apply configuration settings that are shared across all modules.
 */
fun PluginContainer.applyBaseConfig(project: Project) {
    whenPluginAdded {
        when (this) {
            is com.android.build.gradle.internal.plugins.AppPlugin -> {
                project.extensions
                    .getByType<com.android.build.gradle.AppExtension>()
                    .apply {
                        baseConfig()
                    }
            }
            is com.android.build.gradle.internal.plugins.LibraryPlugin -> {
                project.extensions
                    .getByType<com.android.build.gradle.LibraryExtension>()
                    .apply {
                        baseConfig()
                    }
            }
        }
    }
}

But as soon as I move these into gradle/gradle-base-config.gradle.kts, it will no longer compile. I’m assuming because it has no reference to what it is etc, but I can’t find anything anywhere on how to expose this. This also happens for configurations should as jacoco configurations when using apply(from = "${projectDir}/gradle/jacoco.gradle.kts there’s unresolved references in the kts file, but moving it directly into my app build.gradle everything compiles.

Solution

This is unfortunately not supported by kotlin dsl as described here: type safe accessors.

However you can use precompiled script plugins to achieve similar behavior

Answered By – Dave562

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published