https://kotlinlang.org logo
#gradle
Title
# gradle
s

Sam

07/01/2022, 10:49 AM
Good afternoon. Please help me find a solution. I have an android project and I want to move a section from the module level gradle to the project level. I am using Kotlin DSL. I found a solution for Groovy but I can't migrate it to Kotlin.
Copy code
def applyAndroid(project) {
    project.android {

        compileSdkVersion compileVersion

        defaultConfig {
            minSdkVersion minVersion
            targetSdkVersion compileVersion
            versionCode verCode
            versionName verName
            testInstrumentationRunner testRunner
        }

        compileOptions {
            sourceCompatibility = 1.8
            targetCompatibility = 1.8
        }

        kotlinOptions {
            jvmTarget = "1.8"
//            useIR = true
            freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn"
            freeCompilerArgs += "-Xjvm-default=all"
        }

        testOptions.unitTests {
            includeAndroidResources = true
        }

        buildFeatures {
            aidl = false
            renderScript = false
            resValues = false
            shaders = false
        }
    }

}
I have a limitation in the Project class, I can't find an android() method
v

Vampire

07/01/2022, 10:51 AM
That's actually a bad practice for centralizing logic. I'd suggest you have a look at precompiled script plugins instead with which you build convention plugins that you then apply to your project where you want that logic.
Actually there you will have basically the same problem, because
android
in Kotlin DSL is a type-safe accessor that is only generated if you apply the corresponding plugin in the same script using the
plugins { ... }
DSL. So in your convention plugin you either have to also apply the corresponding plugin which makes sense as you also want to configure it, or you need to do it without the sugar of the generated accessor and do something like
configure<AndroidExtensionOrHoweverTheClassNameIs>() { ... }
☝️ 1
s

Sam

07/01/2022, 10:57 AM
I tried in subproject add plugins id("com.android.application") version "7.2.1" apply false id("com.android.library") version "7.2.1" apply false but it did nothing
@Vampire Thanks for pointing the way
v

Vampire

07/01/2022, 12:15 PM
apply false
is not applying, it is just adding to class path, so no accessors would be generated. And besides that, as I said it has to be in the script where the code is to get the accessors in the right scope.
4 Views