如何为 buildSrc 和应用程序模块定义 Kotlin 版本?

How to define the Kotlin version for both buildSrc and an application module?

我在多模块 Kotlin 项目中使用 buildSrc 模块 manage dependency definitions and versions. The module makes use of kotlin-dslbuild.gradle.kts 所示:

plugins {
    `kotlin-dsl`
}

替代声明:

plugins {
    id("org.gradle.kotlin.kotlin-dsl") version "0.16.2"
}

我想使用相同的 Kotlin 版本来编译 buildSrc 模块以及在应用程序 module/s 中。我的第一次尝试是简单地添加 JVM 工件:

plugins {
    `kotlin-dsl`
    kotlin("jvm") version "1.2.31"
}

然而,这会导致构建错误,讨论 here:

Error resolving plugin [id: 'org.jetbrains.kotlin.jvm', version: '1.2.31']
Plugin request for plugin already on the classpath must not include a version

什么是只定义一次整个项目使用的 Kotlin 版本的便捷方法?

相关

我知道的唯一方法是将它放入 gradle.properties(或任何其他配置)并在 settings.gradle.kts pluginManagement 中读取它。像这样:

pluginManagement {
    repositories {
        gradlePluginPortal()
    }
    resolutionStrategy {
        eachPlugin {
            if (requested.id.id.startsWith("org.jetbrains.kotlin")) {
                useVersion(gradle.rootProject.extra["kotlin.version"] as String)
            }
        }
    }
}

错误不言而喻:如果您已经在 buildscript 块中指定了插件版本,则无法在 plugins 文件夹中指定它。

您可以将 kotlinVersion 放入 gradle.properties 并将 buildSrc/gradle.propeties 符号链接到 ./gradle.properties

Each Gradle release is meant to be used with a specific version of the kotlin-dsl plugin and compatibility between arbitrary Gradle releases and kotlin-dsl plugin versions is not guaranteed.

Using an unexpected version of the kotlin-dsl plugin in a build can cause hard to diagnose problems.

Starting with Gradle 5.4, a warning is emitted whenever an unexpected version of the kotlin-dsl plugin is detected.

Paul Merlin @eskatos, 25.04.2019

因此,我删除了 version:

plugins {
    `kotlin-dsl`
}

repositories {
    mavenCentral()
}