Skip to content

LanguageIdiomaภาษา

From Gradle to Gradle.kts

From Gradle to Gradle.ktsDe Gradle a Gradle.ktsจาก Gradle สู่ Gradle.kts

AndroidAndroidAndroid

ByPorโดย David Cruz Anaya, Mobile & Applied AI EngineerIngeniero sénior de móvil e IA aplicada (Android, Kotlin Multiplatform, IA de producto)วิศวกรมือถือและ AI ประยุกต์ระดับอาวุโส (Android, Kotlin Multiplatform, AI ของผลิตภัณฑ์)

Updated 11 July 2026Actualizado el 11 de julio de 2026อัปเดตเมื่อ 11 กรกฎาคม 20265 min read5 min de lecturaอ่าน 5 นาที
AndroidMobile DevelopmentKotlinRustPerformance
Share:Compartir:แชร์:

Gradle to Gradle.kts migration guide banner

Converting a build.gradle file (Groovy) to build.gradle.kts (Kotlin DSL) is mostly mechanical. You wrap function arguments in parentheses, swap single quotes for double quotes, and add an equals sign to every property assignment. A few APIs also have a different Kotlin name, like minifyEnabled becoming isMinifyEnabled.

I first wrote this guide in 2021. Since then Kotlin DSL has become the default build language for new Android projects. That is the path Android Studio already puts you on. I have kept the original side-by-side examples and added a section at the end on what changed by 2026, so the code you copy is still correct today.

Note: I use an Android project in this guide, but the same rules apply to any Kotlin or JVM project built with Gradle.

How to convert build.gradle to build.gradle.kts

The full migration comes down to a handful of repeatable steps. Do them in order and rebuild once at the end.

  1. Rename each build.gradle file to build.gradle.kts. Start with the project-level file, then the module (app) file.
  2. In the project-level file, add gradlePluginPortal() to buildscript.repositories, wrap every classpath dependency in parentheses, and switch to double quotes.
  3. Rewrite the clean task using tasks.register, since the Groovy task clean(type: Delete) syntax does not exist in Kotlin.
  4. In the module file, convert plugins, dependencies, and the android block: add parentheses to functions, double quotes to strings, and an equals sign to every property.
  5. Replace API names that differ in Kotlin, such as minifyEnabled with isMinifyEnabled and debug { } with getByName("debug") { }.
  6. Clean and rebuild the project so the IDE re-syncs against the new script.

The rest of this post is those steps in detail, with Groovy and Kotlin side by side.

How do you convert the project-level build.gradle?

The following snippet shows the same code in Groovy and Kotlin. The changes are small:

  • Add gradlePluginPortal() to buildscript > repositories.
  • Add parentheses to the classpath dependencies and use double quotes (") instead of single quotes (').
  • Refactor the Gradle clean task: use the tasks variable with the register extension function, and pass the task name, the type class, and a lambda action. Add parentheses after delete.
// From Groovy:
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.3"
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31'
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
// To Kotlin:
buildscript {
    repositories {
        gradlePluginPortal() <- add this plugin
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:7.0.3")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31") <- parenthesis and from single to double quotes
    }
}

tasks.register("clean", Delete::class) {
    delete(rootProject.buildDir)
} <- Refactor the code

That converts the project-level build.gradle into .kts.

How do you convert the app-level build.gradle?

Now for the module file. This is where most of the code lives, so I will take it block by block.

Plugins

The plugins block sits at the top of the file:

  • For any id, keep id but add parentheses and double quotes.
  • For Kotlin plugins, replace id with the kotlin("name") helper.
// From Groovy
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
}
// To Kotlin
plugins {
    id("com.android.application") <- Parenthesis and double quotes
    kotlin("android") <- Replace id for Kotlin and double quotes
    kotlin("kapt")
}

Dependencies

Dependencies are simple to update: add parentheses after the dependency handler and use double quotes for the coordinate string. Here are the common handlers side by side.

// Groovy
dependencies {
    implementation project(path: ':your-module')
    implementation 'androidx.core:core-ktx:1.7.0'
    debugImplementation 'androidx.compose.ui:ui-tooling:1.0.5'
    kapt 'androidx.room:room-compiler:2.3.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
}
// Kotlin
dependencies {
    implementation(project(":your-module"))
    implementation("androidx.core:core-ktx:1.7.0")
    debugImplementation("androidx.compose.ui:ui-tooling:1.0.5")
    kapt("androidx.room:room-compiler:2.3.0")
    testImplementation("junit:junit:4.13.2")
    androidTestImplementation("androidx.test.ext:junit:1.1.3")
}

Note how project(path: ':your-module') becomes project(":your-module"). Groovy’s named-argument map syntax collapses into a plain string argument in Kotlin.

Kapt options

If the project uses the kapt Kotlin plugin, you can still toggle flags, but the equals sign is mandatory in Kotlin. Groovy lets you write the assignment with or without it; Kotlin does not.

// From Groovy:
kapt {
    correctErrorTypes true
}
// To Kotlin:
kapt {
    correctErrorTypes = true
}

The android block

This block is the longest, and the changes follow the same three rules:

  • All buildTypes are declared with getByName("debug") instead of a bare debug { }.
  • minifyEnabled becomes isMinifyEnabled.
  • Every property gets an equals sign, every string gets double quotes, and functions like proguardFiles get parentheses.
// From Groovy:
android {
    compileSdk 31

    defaultConfig {
        applicationId "com.domain.appname"
        minSdk 23
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.5.21'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}
// To Kotlin:
android {
    compileSdk = 31

    defaultConfig {
        applicationId = "com.domain.appname"
        minSdk = 23
        targetSdk = 31
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary = true
        }
    }

    buildTypes {
        getByName("debug") { <- change from debug {}
            isMinifyEnabled = false <- change from minifyEnabled
        }
        getByName("release") {
            isMinifyEnabled = true
            proguardFiles( <- add parenthesis
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
        useIR = true
    }
    buildFeatures {
        compose = true
    }
    composeOptions {
        kotlinCompilerExtensionVersion = Versions.Compose
    }
    packagingOptions {
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
}

Why does Android Studio show errors after the conversion?

After you rename the files and update the syntax, Android Studio can show errors even when the script is correct. That is the sync cache, not your code. You can clear it with a clean and rebuild, or by invalidating caches:

Build > Clean Project and Build > Rebuild Project

or

File > Invalidate Caches / Restart

If the errors survive that, they are usually real syntax issues, most often a missing equals sign on a property or a function call left without parentheses.

What changed by 2026?

The conversion rules above still hold, but a few pieces of the surrounding advice have moved on. If you are setting up a build today rather than migrating an old one, keep these in mind. I have left the original code untouched so nothing breaks, and I am flagging the modern equivalents separately.

  • Kotlin DSL is the default. New Android Studio projects are generated with .gradle.kts files out of the box, so for greenfield work there is nothing to convert. Because the script is statically typed, the IDE gives you code completion, refactoring, and click-through navigation into the build API. Groovy build scripts are dynamically typed, so the IDE can only guess.
  • Version catalogs. New projects also ship a gradle/libs.versions.toml catalog, and dependencies are referenced as implementation(libs.androidx.core.ktx) instead of a hardcoded coordinate string. It centralises versions across modules.
  • rootProject.buildDir is deprecated. In current Gradle it is replaced by rootProject.layout.buildDirectory, so a modern clean task reads delete(rootProject.layout.buildDirectory).
  • The Compose compiler is now a plugin. Since Kotlin 2.0, you apply org.jetbrains.kotlin.plugin.compose and the composeOptions.kotlinCompilerExtensionVersion line is no longer required, because the compiler version tracks your Kotlin version.
  • KSP over kapt. Many annotation processors, Room included, now support KSP, which is faster than kapt. Where a library offers it, prefer ksp("...") over kapt("...").

None of that changes how you translate Groovy into Kotlin. It changes what a brand-new file looks like, so treat the examples above as the migration path and this list as the destination.

Happy coding.

David Cruz davthecoder.com

Gradle to Gradle.kts migration guide banner

Convertir un archivo build.gradle (Groovy) en build.gradle.kts (DSL de Kotlin) es, sobre todo, mecánico. Envuelves los argumentos de las funciones entre paréntesis, cambias las comillas simples por comillas dobles y añades un signo de igual a cada asignación de propiedad. Unas pocas API también tienen un nombre distinto en Kotlin, como minifyEnabled, que pasa a ser isMinifyEnabled.

Escribí esta guía por primera vez en 2021. Desde entonces el DSL de Kotlin se ha convertido en el lenguaje de compilación por defecto de los proyectos Android nuevos. Ese es el camino por el que Android Studio ya te pone. He mantenido los ejemplos originales, uno al lado del otro, y he añadido al final una sección sobre lo que cambió hasta 2026, para que el código que copies siga siendo correcto hoy.

Nota: en esta guía uso un proyecto Android, pero las mismas reglas valen para cualquier proyecto de Kotlin o de JVM construido con Gradle.

Cómo convertir build.gradle en build.gradle.kts

La migración completa se reduce a un puñado de pasos que se repiten. Hazlos en orden y recompila una vez al final.

  1. Renombra cada archivo build.gradle a build.gradle.kts. Empieza por el archivo de nivel de proyecto y sigue con el del módulo (app).
  2. En el archivo de nivel de proyecto, añade gradlePluginPortal() a buildscript.repositories, envuelve cada dependencia de classpath entre paréntesis y pasa a comillas dobles.
  3. Reescribe la tarea clean con tasks.register, porque la sintaxis de Groovy task clean(type: Delete) no existe en Kotlin.
  4. En el archivo del módulo, convierte plugins, dependencies y el bloque android: paréntesis en las funciones, comillas dobles en las cadenas y un signo de igual en cada propiedad.
  5. Sustituye los nombres de API que cambian en Kotlin, como minifyEnabled por isMinifyEnabled y debug { } por getByName("debug") { }.
  6. Limpia y recompila el proyecto para que el IDE vuelva a sincronizarse contra el script nuevo.

El resto del artículo son esos pasos en detalle, con Groovy y Kotlin uno al lado del otro.

¿Cómo conviertes el build.gradle de nivel de proyecto?

El fragmento siguiente muestra el mismo código en Groovy y en Kotlin. Los cambios son pequeños:

  • Añade gradlePluginPortal() a buildscript > repositories.
  • Añade paréntesis a las dependencias de classpath y usa comillas dobles (") en lugar de comillas simples (').
  • Refactoriza la tarea clean de Gradle: usa la variable tasks con la función de extensión register, y pasa el nombre de la tarea, la clase del tipo y una acción lambda. Añade paréntesis después de delete.
// From Groovy:
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.3"
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31'
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
// To Kotlin:
buildscript {
    repositories {
        gradlePluginPortal() <- add this plugin
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:7.0.3")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31") <- parenthesis and from single to double quotes
    }
}

tasks.register("clean", Delete::class) {
    delete(rootProject.buildDir)
} <- Refactor the code

Con eso conviertes el build.gradle de nivel de proyecto en .kts.

¿Cómo conviertes el build.gradle de nivel de aplicación?

Ahora el archivo del módulo. Aquí es donde vive la mayor parte del código, así que lo iré bloque a bloque.

Plugins

El bloque plugins va al principio del archivo:

  • En cualquier id, conserva id pero añade paréntesis y comillas dobles.
  • En los plugins de Kotlin, sustituye id por el ayudante kotlin("name").
// From Groovy
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
}
// To Kotlin
plugins {
    id("com.android.application") <- Parenthesis and double quotes
    kotlin("android") <- Replace id for Kotlin and double quotes
    kotlin("kapt")
}

Dependencias

Las dependencias son sencillas de actualizar: añade paréntesis después del manejador de la dependencia y usa comillas dobles en la cadena de coordenadas. Aquí van los manejadores habituales, uno al lado del otro.

// Groovy
dependencies {
    implementation project(path: ':your-module')
    implementation 'androidx.core:core-ktx:1.7.0'
    debugImplementation 'androidx.compose.ui:ui-tooling:1.0.5'
    kapt 'androidx.room:room-compiler:2.3.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
}
// Kotlin
dependencies {
    implementation(project(":your-module"))
    implementation("androidx.core:core-ktx:1.7.0")
    debugImplementation("androidx.compose.ui:ui-tooling:1.0.5")
    kapt("androidx.room:room-compiler:2.3.0")
    testImplementation("junit:junit:4.13.2")
    androidTestImplementation("androidx.test.ext:junit:1.1.3")
}

Fíjate en cómo project(path: ':your-module') pasa a ser project(":your-module"). La sintaxis de mapa con argumentos con nombre de Groovy se reduce a un argumento de cadena corriente en Kotlin.

Opciones de kapt

Si el proyecto usa el plugin kapt de Kotlin, sigues pudiendo activar o desactivar flags, pero el signo de igual es obligatorio en Kotlin. Groovy te deja escribir la asignación con él o sin él; Kotlin, no.

// From Groovy:
kapt {
    correctErrorTypes true
}
// To Kotlin:
kapt {
    correctErrorTypes = true
}

El bloque android

Este bloque es el más largo, y los cambios siguen las mismas tres reglas:

  • Todos los buildTypes se declaran con getByName("debug") en lugar de un debug { } pelado.
  • minifyEnabled pasa a ser isMinifyEnabled.
  • Cada propiedad recibe un signo de igual, cada cadena recibe comillas dobles y funciones como proguardFiles reciben paréntesis.
// From Groovy:
android {
    compileSdk 31

    defaultConfig {
        applicationId "com.domain.appname"
        minSdk 23
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.5.21'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}
// To Kotlin:
android {
    compileSdk = 31

    defaultConfig {
        applicationId = "com.domain.appname"
        minSdk = 23
        targetSdk = 31
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary = true
        }
    }

    buildTypes {
        getByName("debug") { <- change from debug {}
            isMinifyEnabled = false <- change from minifyEnabled
        }
        getByName("release") {
            isMinifyEnabled = true
            proguardFiles( <- add parenthesis
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
        useIR = true
    }
    buildFeatures {
        compose = true
    }
    composeOptions {
        kotlinCompilerExtensionVersion = Versions.Compose
    }
    packagingOptions {
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
}

¿Por qué Android Studio muestra errores después de la conversión?

Después de renombrar los archivos y actualizar la sintaxis, Android Studio puede mostrar errores aunque el script sea correcto. Eso es la caché de sincronización, no tu código. Puedes limpiarla con un clean y una recompilación, o invalidando las cachés:

Build > Clean Project y Build > Rebuild Project

o

File > Invalidate Caches / Restart

Si los errores sobreviven a eso, suelen ser fallos de sintaxis reales, casi siempre un signo de igual que falta en una propiedad o una llamada a función que se quedó sin paréntesis.

¿Qué cambió hasta 2026?

Las reglas de conversión de arriba siguen valiendo, pero algunas piezas del consejo de alrededor han seguido adelante. Si hoy estás montando una compilación, en lugar de migrar una antigua, ten esto presente. He dejado el código original intacto para que nada se rompa, y señalo los equivalentes modernos aparte.

  • El DSL de Kotlin es el predeterminado. Los proyectos nuevos de Android Studio se generan con archivos .gradle.kts de serie, así que en un proyecto desde cero no hay nada que convertir. Como el script tiene tipos estáticos, el IDE te da completado de código, refactorización y navegación con clic hasta la API de compilación. Los scripts de compilación en Groovy tienen tipos dinámicos, así que el IDE solo puede adivinar.
  • Catálogos de versiones. Los proyectos nuevos también traen un catálogo gradle/libs.versions.toml, y las dependencias se referencian como implementation(libs.androidx.core.ktx) en lugar de una cadena de coordenadas escrita a mano. Centraliza las versiones entre módulos.
  • rootProject.buildDir está obsoleto. En el Gradle actual lo sustituye rootProject.layout.buildDirectory, así que una tarea clean moderna se lee delete(rootProject.layout.buildDirectory).
  • El compilador de Compose ahora es un plugin. Desde Kotlin 2.0 aplicas org.jetbrains.kotlin.plugin.compose y la línea composeOptions.kotlinCompilerExtensionVersion ya no hace falta, porque la versión del compilador sigue a tu versión de Kotlin.
  • KSP antes que kapt. Muchos procesadores de anotaciones, Room incluido, ya admiten KSP, que es más rápido que kapt. Donde una biblioteca lo ofrezca, prefiere ksp("...") frente a kapt("...").

Nada de eso cambia cómo traduces Groovy a Kotlin. Cambia el aspecto de un archivo recién creado, así que toma los ejemplos de arriba como el camino de la migración y esta lista como el destino.

¡A programar!

David Cruz davthecoder.com

แบนเนอร์คู่มือย้ายจาก Gradle สู่ Gradle.kts

การแปลงไฟล์ build.gradle (Groovy) เป็น build.gradle.kts (Kotlin DSL) ส่วนใหญ่เป็นงานกลไก คุณหุ้มอาร์กิวเมนต์ของฟังก์ชันด้วยวงเล็บ สลับเครื่องหมายคำพูดเดี่ยวเป็นคู่ และเติมเครื่องหมายเท่ากับให้ทุกการกำหนดพร็อพเพอร์ตี้ API บางตัวมีชื่อ Kotlin คนละชื่อ เช่น minifyEnabled กลายเป็น isMinifyEnabled

ผมเขียนคู่มือนี้ครั้งแรกในปี 2021 ตั้งแต่นั้น Kotlin DSL กลายเป็นภาษาบิลด์เริ่มต้นของโปรเจกต์ Android ใหม่ นั่นคือเส้นทางที่ Android Studio พาคุณไปอยู่แล้ว ผมเก็บตัวอย่างคู่ขนานเดิมไว้ และเพิ่มส่วนท้ายเรื่องสิ่งที่เปลี่ยนภายในปี 2026 เพื่อให้โค้ดที่คุณก็อปยังถูกต้องวันนี้

หมายเหตุ: ผมใช้โปรเจกต์ Android ในคู่มือนี้ แต่กฎเดียวกันใช้กับโปรเจกต์ Kotlin หรือ JVM ใด ๆ ที่บิลด์ด้วย Gradle

วิธีแปลง build.gradle เป็น build.gradle.kts

การย้ายทั้งก้อนลงเอยที่ขั้นตอนซ้ำ ๆ ไม่กี่ขั้น ทำตามลำดับ แล้วบิลด์ใหม่ครั้งเดียวตอนท้าย

  1. เปลี่ยนชื่อไฟล์ build.gradle แต่ละไฟล์เป็น build.gradle.kts เริ่มจากไฟล์ระดับโปรเจกต์ แล้วไฟล์โมดูล (app)
  2. ในไฟล์ระดับโปรเจกต์ เพิ่ม gradlePluginPortal() ใน buildscript.repositories หุ้มทุก classpath dependency ด้วยวงเล็บ และสลับเป็นเครื่องหมายคำพูดคู่
  3. เขียนงาน clean ใหม่ด้วย tasks.register เพราะซินแทกซ์ Groovy task clean(type: Delete) ไม่มีใน Kotlin
  4. ในไฟล์โมดูล แปลง plugins, dependencies และบล็อก android: เติมวงเล็บให้ฟังก์ชัน เครื่องหมายคำพูดคู่ให้สตริง และเครื่องหมายเท่ากับให้ทุกพร็อพเพอร์ตี้
  5. แทนชื่อ API ที่ต่างใน Kotlin เช่น minifyEnabled ด้วย isMinifyEnabled และ debug { } ด้วย getByName("debug") { }
  6. คลีนแล้วบิลด์โปรเจกต์ใหม่ เพื่อให้ IDE ซิงก์กับสคริปต์ใหม่

ที่เหลือของโพสต์นี้คือขั้นตอนเหล่านั้นแบบละเอียด โดยวาง Groovy กับ Kotlin คู่กัน

จะแปลง build.gradle ระดับโปรเจกต์อย่างไร

ตัวอย่างต่อไปแสดงโค้ดเดียวกันใน Groovy และ Kotlin การเปลี่ยนมีขนาดเล็ก:

  • เพิ่ม gradlePluginPortal() ใน buildscript > repositories
  • เติมวงเล็บให้ classpath dependency และใช้เครื่องหมายคำพูดคู่ (") แทนเครื่องหมายคำพูดเดี่ยว (')
  • ปรับงาน clean ของ Gradle: ใช้ตัวแปร tasks กับฟังก์ชันส่วนขยาย register แล้วส่งชื่องาน คลาสชนิด และการกระทำแบบแลมบ์ดา เติมวงเล็บหลัง delete
// From Groovy:
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.3"
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31'
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
// To Kotlin:
buildscript {
    repositories {
        gradlePluginPortal() <- add this plugin
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:7.0.3")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31") <- parenthesis and from single to double quotes
    }
}

tasks.register("clean", Delete::class) {
    delete(rootProject.buildDir)
} <- Refactor the code

นั่นแปลง build.gradle ระดับโปรเจกต์เป็น .kts

จะแปลง build.gradle ระดับแอปอย่างไร

ต่อที่ไฟล์โมดูล นี่คือที่ที่โค้ดส่วนใหญ่อยู่ ดังนั้นผมจะเอาทีละบล็อก

ปลั๊กอิน

บล็อก plugins อยู่บนสุดของไฟล์:

  • สำหรับ id ใด ๆ ให้คง id แต่เติมวงเล็บและเครื่องหมายคำพูดคู่
  • สำหรับปลั๊กอิน Kotlin ให้แทน id ด้วยตัวช่วย kotlin("name")
// From Groovy
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
}
// To Kotlin
plugins {
    id("com.android.application") <- Parenthesis and double quotes
    kotlin("android") <- Replace id for Kotlin and double quotes
    kotlin("kapt")
}

Dependency

Dependency อัปเดตง่าย: เติมวงเล็บหลังตัวจัดการ dependency และใช้เครื่องหมายคำพูดคู่สำหรับสตริงพิกัด นี่คือตัวจัดการที่พบบ่อยวางคู่กัน

// Groovy
dependencies {
    implementation project(path: ':your-module')
    implementation 'androidx.core:core-ktx:1.7.0'
    debugImplementation 'androidx.compose.ui:ui-tooling:1.0.5'
    kapt 'androidx.room:room-compiler:2.3.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
}
// Kotlin
dependencies {
    implementation(project(":your-module"))
    implementation("androidx.core:core-ktx:1.7.0")
    debugImplementation("androidx.compose.ui:ui-tooling:1.0.5")
    kapt("androidx.room:room-compiler:2.3.0")
    testImplementation("junit:junit:4.13.2")
    androidTestImplementation("androidx.test.ext:junit:1.1.3")
}

สังเกตว่า project(path: ':your-module') กลายเป็น project(":your-module") ซินแทกซ์แมปอาร์กิวเมนต์แบบมีชื่อของ Groovy ยุบเป็นอาร์กิวเมนต์สตริงธรรมดาใน Kotlin

ตัวเลือก Kapt

ถ้าโปรเจกต์ใช้ปลั๊กอิน kapt ของ Kotlin คุณยังสลับแฟล็กได้ แต่เครื่องหมายเท่ากับบังคับใน Kotlin Groovy ให้เขียนการกำหนดโดยมีหรือไม่มีมันก็ได้ Kotlin ไม่ให้

// From Groovy:
kapt {
    correctErrorTypes true
}
// To Kotlin:
kapt {
    correctErrorTypes = true
}

บล็อก android

บล็อกนี้ยาวที่สุด และการเปลี่ยนตามสามกฎเดิม:

  • buildTypes ทั้งหมดประกาศด้วย getByName("debug") แทน debug { } เปล่า
  • minifyEnabled กลายเป็น isMinifyEnabled
  • ทุกพร็อพเพอร์ตี้ได้เครื่องหมายเท่ากับ ทุกสตริงได้เครื่องหมายคำพูดคู่ และฟังก์ชันอย่าง proguardFiles ได้วงเล็บ
// From Groovy:
android {
    compileSdk 31

    defaultConfig {
        applicationId "com.domain.appname"
        minSdk 23
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.5.21'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}
// To Kotlin:
android {
    compileSdk = 31

    defaultConfig {
        applicationId = "com.domain.appname"
        minSdk = 23
        targetSdk = 31
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary = true
        }
    }

    buildTypes {
        getByName("debug") { <- change from debug {}
            isMinifyEnabled = false <- change from minifyEnabled
        }
        getByName("release") {
            isMinifyEnabled = true
            proguardFiles( <- add parenthesis
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
        useIR = true
    }
    buildFeatures {
        compose = true
    }
    composeOptions {
        kotlinCompilerExtensionVersion = Versions.Compose
    }
    packagingOptions {
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
}

ทำไม Android Studio แสดงข้อผิดพลาดหลังแปลง

หลังจากคุณเปลี่ยนชื่อไฟล์และอัปเดตซินแทกซ์ Android Studio แสดงข้อผิดพลาดได้แม้สคริปต์จะถูกต้อง นั่นคือแคชการซิงก์ ไม่ใช่โค้ดของคุณ คุณล้างมันด้วยคลีนแล้วบิลด์ใหม่ หรือด้วยการทำให้แคชใช้ไม่ได้:

Build > Clean Project และ Build > Rebuild Project

หรือ

File > Invalidate Caches / Restart

ถ้าข้อผิดพลาดรอดสิ่งนั้นไปได้ โดยปกติมันเป็นปัญหาซินแทกซ์จริง ส่วนใหญ่คือเครื่องหมายเท่ากับที่หายบนพร็อพเพอร์ตี้ หรือการเรียกฟังก์ชันที่ไม่มีวงเล็บ

อะไรเปลี่ยนภายในปี 2026

กฎการแปลงด้านบนยังใช้ได้ แต่คำแนะนำรอบ ๆ บางชิ้นเดินหน้าไปแล้ว ถ้าคุณกำลังตั้งบิลด์วันนี้แทนที่จะย้ายของเก่า ให้จำสิ่งเหล่านี้ ผมปล่อยโค้ดเดิมไว้ไม่แตะเพื่อไม่ให้มีอะไรพัง และผมชี้ตัวที่เทียบเท่าแบบสมัยใหม่แยกต่างหาก

  • Kotlin DSL เป็นค่าเริ่มต้น โปรเจกต์ Android Studio ใหม่ถูกสร้างพร้อมไฟล์ .gradle.kts ตั้งแต่ต้น ดังนั้นสำหรับงานกรีนฟิลด์ไม่มีอะไรให้แปลง เพราะสคริปต์มีชนิดแบบสถิต IDE ให้การเติมโค้ด การรีแฟกเตอร์ และการคลิกทะลุเข้า API ของบิลด์ สคริปต์บิลด์ Groovy มีชนิดแบบไดนามิก ดังนั้น IDE เดาได้อย่างเดียว
  • แคตตาล็อกเวอร์ชัน โปรเจกต์ใหม่ยังส่งแคตตาล็อก gradle/libs.versions.toml มาด้วย และ dependency ถูกอ้างเป็น implementation(libs.androidx.core.ktx) แทนสตริงพิกัดที่เขียนตายตัว มันรวมเวอร์ชันข้ามโมดูลไว้จุดเดียว
  • rootProject.buildDir ถูกเลิกใช้ ใน Gradle ปัจจุบันมันถูกแทนด้วย rootProject.layout.buildDirectory ดังนั้นงาน clean สมัยใหม่อ่านว่า delete(rootProject.layout.buildDirectory)
  • คอมไพเลอร์ Compose ตอนนี้เป็นปลั๊กอิน ตั้งแต่ Kotlin 2.0 คุณใส่ org.jetbrains.kotlin.plugin.compose และบรรทัด composeOptions.kotlinCompilerExtensionVersion ไม่จำเป็นอีก เพราะเวอร์ชันคอมไพเลอร์เดินตามเวอร์ชัน Kotlin ของคุณ
  • KSP เหนือ kapt ตัวประมวลผลแอโนเทชันหลายตัว รวม Room ตอนนี้รองรับ KSP ซึ่งเร็วกว่า kapt ที่ไลบรารีมีให้ เลือก ksp("...") แทน kapt("...")

ไม่มีสิ่งนั้นเปลี่ยนวิธีที่คุณแปล Groovy เป็น Kotlin มันเปลี่ยนว่าไฟล์ใหม่เอี่ยมหน้าตาเป็นอย่างไร ดังนั้นถือว่าตัวอย่างด้านบนเป็นเส้นทางการย้าย และลิสต์นี้เป็นปลายทาง

เขียนโค้ดให้สนุก

David Cruz davthecoder.com

Share:Compartir:แชร์:

CommentsComentariosความคิดเห็น

Loading comments…Cargando comentarios…กำลังโหลดความคิดเห็น…