The Configuration DSL pattern helps you write easy-to-read code that sets up settings or options in a clear way, like filling out a form.
Configuration DSL pattern in Kotlin
class Config { var option1: String = "" var option2: Int = 0 fun build(block: Config.() -> Unit): Config { block() return this } } // Usage: val config = Config().build { option1 = "Hello" option2 = 42 }
The block is a function that runs with Config as its receiver, so you can set properties directly.
This pattern makes configuration code look clean and easy to read.
class ServerConfig { var host: String = "localhost" var port: Int = 8080 fun configure(block: ServerConfig.() -> Unit): ServerConfig { block() return this } } val server = ServerConfig().configure { host = "192.168.1.1" port = 9090 }
class DatabaseConfig { var url: String = "" var user: String = "" var password: String = "" fun setup(block: DatabaseConfig.() -> Unit): DatabaseConfig { block() return this } } val dbConfig = DatabaseConfig().setup { url = "jdbc:mysql://localhost:3306/mydb" user = "root" password = "secret" }
This program creates an email configuration using the DSL pattern. It sets the SMTP server, port, and SSL option inside a block, then prints the settings.
class EmailConfig { var smtpServer: String = "" var port: Int = 25 var useSSL: Boolean = false fun configure(block: EmailConfig.() -> Unit): EmailConfig { block() return this } } fun main() { val emailConfig = EmailConfig().configure { smtpServer = "smtp.example.com" port = 587 useSSL = true } println("SMTP Server: ${emailConfig.smtpServer}") println("Port: ${emailConfig.port}") println("Use SSL: ${emailConfig.useSSL}") }
You can add default values to make configuration easier.
The block uses this as the receiver, so you can access properties directly without extra names.
This pattern improves code readability and reduces errors in setting options.
The Configuration DSL pattern helps write clear and simple setup code.
It uses a block with the configuration object as receiver to set options easily.
This makes your code look like a small language for configuring things.