Gradle Kotlin DSL unresolved references defined in buildSrc

Viewed 1008

I'm experimenting with Kotlin DSL but I can't get it to recognize objects I defined in buildSrc. They get resolved by the IDE but when I compile the code it doesn't work.

This is the my project structure:

build.gradle.kts
settings.gradle.kts
+buildSrc
    build.gradle.kts
    +src
        +main
            +java
                Dependencies.kt
                Versions.kt
+module1
    build.gradle.kts
+module2
    build.gradle.kts
    

Content of Dependencies.kt:

/**
 * To define plugins
 */
object BuildPlugins {
    val gradle by lazy { "com.android.tools.build:gradle:${Versions.gradlePlugin}" }
    val kotlinGradle by lazy { "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}" }
    val safeArgs by lazy { "androidx.navigation:navigation-safe-args-gradle-plugin:${Versions.safeArgs}" }
}

/**
 * To define dependencies
 */
object Deps {
    val appCompat by lazy { "androidx.appcompat:appcompat:${Versions.appCompat}" }
    val core by lazy { "androidx.core:core-ktx:${Versions.core}" }
    val timber by lazy { "com.jakewharton.timber:timber:${Versions.timber}" }
    val kotlin by lazy { "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${Versions.kotlin}" }
    val material by lazy { "com.google.android.material:material:${Versions.material}" }
    val constraintLayout by lazy { "androidx.constraintlayout:constraintlayout:${Versions.constraintLayout}" }
}

Project wide build.gradle.kts (the one which fails first):

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        BuildPlugins.gradle
        BuildPlugins.kotlinGradle
        BuildPlugins.safeArgs

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
...

I also want to point out that the android { ... } block is not recognized in the modules gradle files but I think that may be because of the failed compilation.

1 Answers

You have Kotlin files under src/main/java. They should be in src/main/kotlin and you will need to include Kotlin build support in the buildSrc Gradle file (maybe you have this, you didn't show what's in buildSrc/build.gradle.kts)

plugins {
    `kotlin-dsl`
}

repositories {
    mavenCentral()
}
Related