For describing Gradle build scripts, we can use Kotlin via build.gradle.kts files. It's a common problem to globally define the Kotlin version to be used, both in the dependencies and also in the build plugin section (It's rather uncommon to have different versions in use for the given case).

Consider the following code (Gradle 4.3.1):

plugins {
    var pluginVersion = "1.2.30"
    kotlin("jvm").version(kotlinVersion)
    // more
}

var dependencyVersion = "1.2.30"
dependencies {
    compile(kotlin("stdlib", kotlinVersion))
    compile(kotlin("reflect", kotlinVersion))
    testCompile(kotlin("test", kotlinVersion))
    // more
}

如您所见,kotlin version(本例中为1.2.30)的定义为twice:dependencyVersionpluginVersion,通常为does not differ.由于DSL限制,无法从plugins块外部访问pluginVersion或从plugins块内部访问dependencyVersion.

How can the version string, "1.2.30" be extracted to a single place?

推荐答案

在Gradle的更高版本中,您不再需要指定kotlin(stdlib|reflect|test)个依赖项的版本,Kotlin插件将自动为您配置它们.

至于将依赖项提取到单个位置,主要有两种模式:

  • 定义要在buildSrc/src/main/kotlin/%的对象中共享的常量,并在构建脚本中使用该对象,buildSrc中的代码可用于整个脚本,包括plugins中的挡路
  • 使用系统属性,您可以在gradle.properties中定义系统属性,在其名称前加上systemProp.,并且可以通过System.getProperties()访问系统属性,例如:

    // build.gradle.kts
    plugins {
      val kotlinVersion by System.getProperties()
      println("Kotlin version is $kotlinVersion")
    }
    
    // gradle.properties
    systemProp.kotlinVersion=1.2.20
    

Kotlin相关问答推荐

可以从背景图像中点击图标吗?

Kotlin - 什么时候和什么时候不喜欢内联函数,为什么?

为什么Kotlin不用static inner class来实现带有object关键字的单例呢?

如何在 Jetpack Compose 中启动和停止动画

按钮无法在 Android Studio 上打开新活动

Kotlin 可空泛型

在 kotlin 中重载函数时,我在一些非常基本的代码上不断收到类型不匹配

如何为你的 Flutter 元素添加 Kotlin 支持?

从代码块执行和返回(在 Elvis 运算符之后)

ActivityOptions.makeSceneTransitionAnimation 在具有多个视图的 kotlin 中不起作用

验证和 DDD - kotlin 数据类

Kotlin中的测试无法访问受保护(protected)的方法

kotlin RecyclerView分页

参数不匹配;SimpleXML

如何在Kotlin中获得KType?

项目未与 Gradle 链接

Kotlin:相互递归函数的尾部递归

内联 Kotlin 方法没有覆盖报告

如何判断数据是否插入到房间数据库中

RxJava2 UndeliverableException 在获取数据时发生方向变化