KOGE

Kotlin Script (KTS) and DSL

Introduction to Kotlin Script (KTS) and DSL

In April 2023, at the Kotlin Conf, it was announced that “Kotlin DSL is now the default for new Gradle builds.” Kotlin was integrated into Gradle’s build tools as early as 2016 and has become the default choice for developers in 2023.

This section explores the origins and development of Kotlin Script and DSL, providing insights into *.gradle.kts files.

Generic KTS Scripts

KTS, or Kotlin Script, is often mistakenly thought to be limited to Gradle scripts. However, *.kts files are versatile Kotlin scripts used in various domains. Similar to Shell or Python scripts, KTS offers uniformity and ease of use, with the added ability to reference external dependencies. The downside is that systems need to install Kotlin dependencies, which are not typically pre-installed.

There are two main KTS standards:

Examples of KTS in use:

  1. “rock3r/deep-clean”@SebastianoPoggi
  2. “kotlin-script-examples”@Kotlin

For a detailed comparison and history of these standards, refer to:

Generic Kotlin DSL

Like KTS, Kotlin DSL is not confined to Gradle scripts and can be found in many other areas. To understand its application, it’s important to know the fundamental elements that make up Kotlin DSL. The following articles and documents offer a comprehensive look at Kotlin DSL, from high-order functions to Type-safe builders:

  1. “High-order functions and lambdas”@Kotlin
  2. “Type-safe builders”@Kotlin
  3. [“Kotlin DSL Introduction”@GlennSandoval](https://medium.com/kotlin-and-kotlin-for-android/kotlin-dsl-introduction-6123c43ae770)
  4. “Domain-Specific Languages In Kotlin: Getting Started”@TinoBalint

Kotlin DSL is also implemented in these well-known libraries:

  1. “Koin”@InsertKoinIO
  2. “Ktor”@Kotlin

*.gradle.kts

Gradle Kotlin DSL is built on generic KTS scripts, further defining the script’s Context (like Project and Settings objects) and adding DSL features for simplified configurations. The following resources provide extensive information on Gradle Kotlin DSL, migration from Groovy to Kotlin, and developing plugins with Kotlin:

  1. “Gradle Kotlin DSL Primer”@Gradle
  2. “Migrating build logic from Groovy to Kotlin”@Gradle
  3. “Migrating Build Configurations from Groovy to KTS”@Android
  4. “gradle/kotlin-dsl-samples”@Gradle
  5. “Delegated properties”@Kotlin
  6. “Mixing Groovy and Kotlin in Plugin Development”@小灵通 (in Simplified Chinese)

Summary

Understanding generic Kotlin Script and DSL can bring significant convenience to our work, allowing one language to meet multiple job requirements. While official support isn’t exclusively for KTS, as mentioned earlier, Gradle Kotlin DSL is the recommended approach by three major companies. For plugin development, Kotlin is widely supported, offering higher readability, better compile-time checks, and improved IDE support compared to Groovy.