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

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

我将向您展示root项目的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类似,但有一些不同之处。 阅读他们的文档 ,看看例子 。

就你而言,问题是:

  1. ext.kotlin_version不是有效的Kotlin语法,请使用方括号
  2. 所有Kotlin字符串都使用双引号
  3. 在大多数函数调用的参数周围都需要大括号(也有例外,如中缀函数 )
  4. 极其不同的任务管理API。 有不同的风格可用。 您可以将任务块中的所有任务都声明为字符串 ,或者使用单个类型的函数,如下例所示。

看看转换后的顶层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) }