Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved references of buildSrc kotlin constants after migration to gradle kotlin dsl

I´m trying to migrate my android project to using gradle kotlin dsl, replacing all build.gradle files with build.gradle.kts files and using kotlin there. Already before, I used to have a kotlin file containing object elements with library and version constants (in buildSrc -> src -> main -> kotlin), like:

object Versions {
    const val anyLibVersion = "1.0.0"
}

object Lib {
    const val anyLib = "x:y:${Versions.anyLibVersion}"
}

In build.gradle files, I can access these constants without problems, but as soon as I switch them to build.gradle.kts, it cannot resolve them anymore. Any explaination for that?

like image 552
Lemao1981 Avatar asked Oct 28 '18 10:10

Lemao1981


3 Answers

What you'd typically have is following in buildSrc/build.gradle.kts

import org.gradle.kotlin.dsl.`kotlin-dsl`

repositories {
    jcenter()
}

plugins {
    `kotlin-dsl`
}

and then have your versions/dependencies in say buildSrc/src/main/java/Dependencies.kt

like image 103
John O'Reilly Avatar answered Nov 17 '22 20:11

John O'Reilly


You can fix it by completely removing the android {} block, doing a Gradle sync, and then adding the code block back.

like image 3
Antoine Avatar answered Nov 17 '22 19:11

Antoine


Does NOT treat the buildSrc directory as an module in settings.gradle.kts (.)


Precompiled script plugins.

Then for apply from in Kotlin DSL, you should use plugins {}

build.gradle.kts (X:buildSrc)

plugins {
    `java-gradle-plugin`
    `kotlin-dsl`
    `kotlin-dsl-precompiled-script-plugins`
}

repositories {
    mavenCentral()
}

Precondition

buildSrc/src/resources/META-INF/gradlePlugins/some-package-id.properties file:

implementation-class=gradlePlugins.android.AndroidLibraryPlugin

buildSrc/src/main/kotlin/gradlePlugins/android/AndroidLibraryPlugin.kt

Pay attention to the package of implementation-class will be "some-package-id"

package gradlePlugins.android

import org.gradle.api.Plugin
import org.gradle.api.Project

class AndroidLibraryPlugin : Plugin<Project> {

    override fun apply(project: Project) {
        project.configurePlugins()
        project.configureAndroid()
        project.configureDependencies()
    }

}

Consume the plugin:

Check that "some-package-id" will be the file name of some-package-id.properties

feature.gradle.kts

plugins {
    id("some-package-id")
}

GL

  • Precompiled script plugins
  • Use buildSrc to abstract imperative logic
  • Kotlin Dsl Samples
  • Source
  • Commit
like image 3
Braian Coronel Avatar answered Nov 17 '22 20:11

Braian Coronel