kotlin-dsl

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Kotlin DSL Skill

Kotlin DSL 技能

Build type-safe DSLs with Kotlin's language features.
利用Kotlin的语言特性构建类型安全的DSL。

Topics Covered

涵盖主题

@DslMarker for Scope Control

使用@DslMarker进行作用域控制

kotlin
@DslMarker
annotation class HtmlDsl

@HtmlDsl
class HTML { fun body(block: Body.() -> Unit) { } }

@HtmlDsl
class Body { fun p(text: String) { } }

// Usage - scoped correctly
html { body { p("Text") } }
kotlin
@DslMarker
annotation class HtmlDsl

@HtmlDsl
class HTML { fun body(block: Body.() -> Unit) { } }

@HtmlDsl
class Body { fun p(text: String) { } }

// Usage - scoped correctly
html { body { p("Text") } }

Gradle Convention Plugin

Gradle约定插件

kotlin
// kotlin-library.gradle.kts
plugins { kotlin("jvm"); `java-library` }

kotlin { jvmToolchain(17) }

dependencies {
    testImplementation(kotlin("test"))
    testImplementation("io.mockk:mockk:1.13.9")
}

tasks.test { useJUnitPlatform() }
kotlin
// kotlin-library.gradle.kts
plugins { kotlin("jvm"); `java-library` }

kotlin { jvmToolchain(17) }

dependencies {
    testImplementation(kotlin("test"))
    testImplementation("io.mockk:mockk:1.13.9")
}

tasks.test { useJUnitPlatform() }

Type-Safe Config Builder

类型安全配置构建器

kotlin
@ConfigDsl
class ServerConfig private constructor(val host: String, val port: Int) {
    class Builder {
        var host = "localhost"
        var port = 8080
        fun build() = ServerConfig(host, port)
    }
}

fun serverConfig(block: ServerConfig.Builder.() -> Unit) =
    ServerConfig.Builder().apply(block).build()

// Usage
val config = serverConfig { host = "api.example.com"; port = 443 }
kotlin
@ConfigDsl
class ServerConfig private constructor(val host: String, val port: Int) {
    class Builder {
        var host = "localhost"
        var port = 8080
        fun build() = ServerConfig(host, port)
    }
}

fun serverConfig(block: ServerConfig.Builder.() -> Unit) =
    ServerConfig.Builder().apply(block).build()

// Usage
val config = serverConfig { host = "api.example.com"; port = 443 }

Troubleshooting

故障排除

IssueResolution
Scope pollutionAdd @DslMarker annotation
Gradle cache staleRun ./gradlew --stop
问题解决方法
作用域污染添加@DslMarker注解
Gradle缓存过期运行./gradlew --stop

Usage

使用方法

Skill("kotlin-dsl")
Skill("kotlin-dsl")