Problem Statement
How do you create type-safe DSL builders in Kotlin using lambda receivers and extension functions?
Explanation
DSL builders use lambda with receiver syntax where the lambda has a receiver type making this refer to that type inside the lambda body, like html open curly body open curly div open curly plus text close curly close curly close curly. The receiver type provides context and available functions creating a domain-specific language.
Create DSLs by defining builder classes with extension functions and using function types with receivers like HTML dot open paren close paren arrow Unit. Mark DSL functions with at DslMarker annotation preventing implicit this from outer scopes, ensuring only the current scope's functions are accessible without qualification.
Use apply, with, or custom functions returning receivers to chain builder calls fluently. Restrict function visibility with annotations or internal modifiers to prevent calling builder functions outside their intended context, maintaining type safety throughout the DSL.
DSL builders are powerful for creating readable configuration APIs like Gradle build scripts written in Kotlin, HTML builders, or test setup code. They make complex nested structures readable and provide compile-time safety unlike string-based or reflection-based approaches.
