Search code examples
gradlegradle-kotlin-dsl

How to apply shared dependencies in gradle kotlin dsl


I'am trying to migrate my Gradle Groovy into Kotlin dsl but I got an error on applying shared dependencies, I'm using multi module project.

apply from ("../shared_dependencies.gradle.kts")

I got function invocation apply() expected, but what does that mean?


Solution

  • A simple Kotlin way of achieving the same result is creating DependencyHandler extension functions within buildSrc module, e.g.:

    fun DependencyHandler.applySharedDeps() {
        add("implementation", "com.some.dependency:version")
    }
    

    If you don't like the add method, you can create a further extension function:

    private fun DependencyHandler.implementation(dependency: Any) {
        add("implementation", dependency)
    }
    fun DependencyHandler.applySharedDeps() {
        implementation("com.some.dependency:version")
    }
    

    Then you can simply call applySharedDeps in any module config:

    dependencies {
        applySharedDeps()
    }
    

    If you also want to apply other configs, and not just dependencies, you can similarly create extension functions for other classes, even the Project class.