18

I have created a versions.gradle.kts just like that:

object Defines {
     const val kotlinVersion = "1.2.61"
     const val junitVersion = "5.3.0"
}

Now I want to import and use that files like that:

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

group = "io.github.deglans"
version = "0.0.1-SNAPSHOT"

plugins {
    application
    kotlin("jvm") version Defines.kotlinVersion
}

application {
    mainClassName = "io.github.deglans.polishnotation.MainKt"
}

dependencies {
    compile(kotlin("stdlib-jdk8"))
    testCompile("org.junit.jupiter", "junit-jupiter-api", Defines.junitVersion)
    testRuntime("org.junit.jupiter", "junit-jupiter-engine", Defines.junitVersion)
}

tasks.withType<KotlinCompile> {
    kotlinOptions.jvmTarget = "1.8"
}

How can I do that?

NOTE: I have already seen this post but it is not exactly that I search...

Deglans Dalpasso
  • 495
  • 5
  • 14
  • Two things are not clear for me: 1) Why do you define the version in the separate file? Wouldn't be enough to define the versions e.g. in the `gradle.properties` file? Or in the `extra` (ExtraPropertiesExtension)? 2) Why do you want to wrap those versions inside the `Defines` object? Why not to use just simple plain `val`s? – Vít Kotačka Sep 19 '18 at 20:54

1 Answers1

8

While I think it should be possible to import another gradle.kts file, I couldn't get it to work properly.

However, I did manage to define my dependencies in a separate Kotlin file in the buildSrc directory.

  1. Create a buildSrc folder in the root of your project (same level as build.gradle.kts)
  2. Add a build.gradle.kts in that buildSrc folder. Here, you need to define the kotlin-dsl plugin. You also need to define the repository where to get the plugin.
plugins {
    `kotlin-dsl`
}

repositories {
    mavenCentral()
}
  1. Create a Kotlin file where you define your dependencies in src/main/kotlin inside the buildSrcfolder. You need to create a normal Kotlin .kt file, not a gradle.kts.

Reimport your Gradle config and you can now use the variables you defined in your Kotlin file created in step #3 in your build.gradle.kts.

Wyko
  • 577
  • 5
  • 13
  • i think that is related to the case when using/including the versions.gradle.kts into a build.gradle.kts. i have a similar issue, in this case (outside of this question) is related to include plugin configs into build.gradle.kts files -- using the function apply from .gradle/groovy or similar – Marlon López Feb 10 '23 at 16:56