Lesson 8 of 9 · 22m
Kotlin DSLs and Type-Safe Configuration That Do Not Become Write-Only Code
Use builders, receivers, and type-safe configuration where they clarify intent, while avoiding clever DSLs that hide operational behavior.
Kotlin DSLs are seductive because the first demo always looks beautiful. Then somebody builds a routing-validation-transaction-permission DSL, nobody can debug it, and the original author becomes a permanent support queue. A good server-side DSL makes common correct usage easy. A bad one hides control flow from the people who need it most.
A DSL should model a narrow vocabulary
Gradle and Ktor work because their vocabulary is stable: dependencies, routes, plugins, installation. Your internal DSL needs the same constraint. It should express what is being configured, not secretly decide when and where execution happens.
data class RetrySpec(val attempts: Int, val initialDelay: Duration)
class RetryBuilder {
var attempts: Int = 3
var initialDelay: Duration = 100.milliseconds
fun build(): RetrySpec {
require(attempts in 1..10) { "attempts must be 1..10" }
return RetrySpec(attempts, initialDelay)
}
}
fun retry(block: RetryBuilder.() -> Unit): RetrySpec =
RetryBuilder().apply(block).build()Usage stays readable without concealing the result:
val policy = retry { attempts = 4; initialDelay = 250.milliseconds }Receivers are powerful because they are invisible
apply, with, and DSL receivers make configuration concise, but they also make implicit scope confusing. In nested builders, a property can resolve to an outer receiver unexpectedly. Kotlin's @DslMarker helps prevent that leakage:
@DslMarker
annotation class ServiceDslUse it on builder classes when nesting is possible. The compiler becomes the documentation you forgot to write.
Prefer typed configuration over stringly typed indirection
data class ServiceConfig(val databaseUrl: String, val databasePoolSize: Int, val redisUrl: String?)
fun loadConfig(): ServiceConfig = ServiceConfig(
databaseUrl = requiredEnv("DATABASE_URL"),
databasePoolSize = envInt("DATABASE_POOL_SIZE", default = 10),
redisUrl = System.getenv("REDIS_URL"),
)Configuration should fail fast, carry units in types, and avoid secrets in logs. If a setting is operational, name it plainly. If it is a deployment concern, do not bury it behind programmatic composition that only one developer understands.
Field notes
- Type-safe builders are excellent for request construction, test fixtures, route wiring, and operational config.
- Avoid extension functions that make every object look magical; discoverability matters more than cleverness.
- Validate at
build()time, not lazily at first use after deployment. - Keep DSL-generated objects immutable where possible. Builders mutate; domain objects should usually not.
Was this lesson helpful?