groovy - 将现有的 groovy build.gradle 文件转换为基于 kotlin 的 build.gradle.kts

标签 groovy kotlin gradle-kotlin-dsl

我的项目有两个用 groovy 语法编写的不同 build.gradle 文件。 我想将这个 groovy 编写的 gradle 文件更改为使用 Kotlin 语法 (build.gradle.kts) 编写的 gradle 文件。

我将向您展示根项目 build.gradle 文件。

    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    //ext.kotlin_version = '1.2-M2'
    ext.kotlin_version = '1.1.51'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0-alpha01'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

我尝试了几种在互联网上找到的“方法”,但都没有奏效。重命名文件,这显然不是解决方案,没有帮助。我在我的根项目中创建了一个新的 build.gradle.kts 文件,但该文件未显示在我的项目中。 gradle 也无法识别新文件。

所以我的问题是:如何将我的 groovy build.gradle 文件转换为 kotlin build.gradle.kts 并将这个新文件添加到我现有的项目中?

感谢您的帮助。

最佳答案

当然,重命名无济于事。您需要使用 Kotlin DSL 重新编写它。它类似于 Groovy,但有一些不同。 Read their docs ,看the examples .

在你的情况下,问题是:

  1. ext.kotlin_version 不是有效的 Kotlin 语法,请使用 square brackets
  2. 全部 Kotlin strings使用双引号
  3. most function calls 的参数需要用大括号括起来(也有异常(exception),例如 infix functions )
  4. 略有不同的任务管理 API。有不同的样式可供选择。您可以申报all the tasks in tasks block as strings ,或使用单一类型的函数,如下例所示。

看一下转换后的顶层build.gradle.kts:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext["kotlin_version"] = "1.1.51"
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath ("com.android.tools.build:gradle:3.1.0-alpha01")
        classpath ("org.jetbrains.kotlin:kotlin-gradle-plugin:${ext["kotlin_version"]}")
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task<Delete>("clean") {
    delete(rootProject.buildDir)
}

关于groovy - 将现有的 groovy build.gradle 文件转换为基于 kotlin 的 build.gradle.kts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47136876/

相关文章:

groovy - Logback.groovy LogstashEncoder 更改字段名称

git - 在 Jenkins 中动态填充 'Multi Select' 参数 ('Extended Choice Parameter' 插件)

android - 如何对使用上下文的类进行单元测试?

sorting - 如何按 Kotlin 中的值对 LinkedHashMap 进行排序?

kotlin - Gradle Kotlin DSL扩展自

xml - 如何访问父 XML 元素

grails - Cobertura覆盖Grails

java - Java 中的联合类型

gradle - 如何将 Gradle 中的原生 JUnit 5 支持与 Kotlin DSL 结合使用?

java - 如何从父项目定义 Gradle kotlin dsl 中的公共(public)依赖项?