📖 Scenario: Imagine you are creating a small Kotlin program to configure a coffee machine. You want to set options like coffee type, size, and sugar level using a simple and readable configuration style called a DSL (Domain Specific Language).
🎯 Goal: Build a Kotlin configuration DSL that lets you set coffee options in a clear and easy way, then print the chosen settings.
📋 What You'll Learn
Create a data class called CoffeeConfig with properties type, size, and sugar.
Create a function called coffeeConfig that takes a lambda with receiver of CoffeeConfig.
Inside the lambda, allow setting the properties type, size, and sugar.
Print the final coffee configuration in a readable format.
💡 Why This Matters
🌍 Real World
Configuration DSLs make it easy to set up options in a readable way, like configuring build tools, UI components, or server settings.
💼 Career
Understanding how to create and use DSLs in Kotlin is useful for Android developers and backend engineers who want to write clean, expressive configuration code.
Progress0 / 4 steps
1
Create the CoffeeConfig data class
Create a Kotlin data class called CoffeeConfig with three mutable properties: type of type String initialized to "Espresso", size of type String initialized to "Medium", and sugar of type Int initialized to 1.
Kotlin
Hint
Use data class CoffeeConfig(var type: String = "Espresso", var size: String = "Medium", var sugar: Int = 1) to create the class.
2
Create the coffeeConfig function
Create a function called coffeeConfig that takes a lambda with receiver of type CoffeeConfig and returns a CoffeeConfig object. Inside the function, create a new CoffeeConfig instance, apply the lambda to it, and return it.
Kotlin
Hint
Define fun coffeeConfig(block: CoffeeConfig.() -> Unit): CoffeeConfig and use config.block() to apply the lambda.
3
Use the DSL to set coffee options
Use the coffeeConfig function to create a CoffeeConfig object called myCoffee. Inside the lambda, set type to "Latte", size to "Large", and sugar to 2.
Kotlin
Hint
Call coffeeConfig { type = "Latte"; size = "Large"; sugar = 2 } and assign it to myCoffee.
4
Print the coffee configuration
Print the coffee configuration stored in myCoffee using println. Format the output exactly as: "Coffee type: Latte, Size: Large, Sugar: 2".
Kotlin
Hint
Use println("Coffee type: ${myCoffee.type}, Size: ${myCoffee.size}, Sugar: ${myCoffee.sugar}") to print the configuration.
Practice
(1/5)
1. What is the main purpose of the Configuration DSL pattern in Kotlin?
easy
A. To write complex algorithms for data processing
B. To handle exceptions in a program
C. To create a simple and readable way to set up configuration using blocks
D. To manage database connections automatically
Solution
Step 1: Understand the Configuration DSL pattern
This pattern is designed to make configuration code simple and clear by using blocks with a configuration object as receiver.
Step 2: Identify the main purpose
The main goal is to write setup code that looks like a small language, making it easy to read and write configurations.
Final Answer:
To create a simple and readable way to set up configuration using blocks -> Option C
Quick Check:
Configuration DSL = simple setup blocks [OK]
Hint: Think: configuration setup made easy and readable [OK]
Common Mistakes:
Confusing DSL with general programming logic
Thinking it manages databases or exceptions
Assuming it is for algorithm implementation
2. Which Kotlin syntax correctly defines a configuration DSL block with a receiver?
easy
A. fun configure(block: () -> Unit) { block() }
B. fun configure(block: () -> Config) { val config = block() }
C. fun configure(block: Config) { block() }
D. fun configure(block: Config.() -> Unit) { val config = Config(); config.block() }
Solution
Step 1: Identify the correct DSL block signature
A configuration DSL block uses a receiver function type like Config.() -> Unit to allow calling config properties inside the block.
Step 2: Check the function implementation
fun configure(block: Config.() -> Unit) { val config = Config(); config.block() } creates a Config instance and calls the block with config as receiver, which is the correct pattern.
Final Answer:
fun configure(block: Config.() -> Unit) { val config = Config(); config.block() } -> Option D
Quick Check:
Receiver function type = fun configure(block: Config.() -> Unit) { val config = Config(); config.block() } [OK]
Hint: Look for Config.() -> Unit receiver syntax [OK]
Common Mistakes:
Using () -> Config instead of Config.() -> Unit
Passing Config instance as parameter instead of receiver
Omitting the receiver call inside the function
3. Given the code below, what is the output?
class Config { var name = ""; var enabled = false }
fun configure(block: Config.() -> Unit): Config {
val config = Config()
config.block()
return config
}
fun main() {
val c = configure {
name = "Test"
enabled = true
}
println("Name: ${c.name}, Enabled: ${c.enabled}")
}
medium
A. Name: Test, Enabled: true
B. Name: , Enabled: false
C. Name: Test, Enabled: false
D. Compilation error
Solution
Step 1: Understand the configure function
The configure function creates a Config object, applies the block to set properties, then returns it.
Step 2: Analyze the block in main
The block sets name to "Test" and enabled to true on the Config instance.
Step 3: Check the printed output
Printing c.name and c.enabled shows "Test" and true respectively.
Hint: Block sets properties on Config instance returned [OK]
Common Mistakes:
Assuming default values remain unchanged
Thinking block does not modify config
Confusing syntax causing compilation error
4. What is wrong with this configuration DSL usage?
class Config { var port = 0 }
fun configure(block: Config.() -> Unit): Config {
val config = Config()
block()
return config
}
fun main() {
val c = configure {
port = 8080
}
println(c.port)
}
medium
A. The block is called without receiver, so port is not set
B. Config class is missing a constructor
C. The configure function should return Unit, not Config
D. The println statement is incorrect
Solution
Step 1: Check how block is called inside configure
The block is called as block() without receiver, so it does not modify the config instance.
Step 2: Understand the effect on port property
Since the block does not apply to config, port remains 0, the default value.
Final Answer:
The block is called without receiver, so port is not set -> Option A
Quick Check:
Missing receiver call = The block is called without receiver, so port is not set [OK]
Hint: Call block with config.block() to apply receiver [OK]
Common Mistakes:
Calling block() instead of config.block()
Assuming default constructor is missing
Thinking return type causes error
5. How can you extend the Configuration DSL pattern to support nested configuration blocks for a server with database settings? Choose the best approach.
hard
A. Use global variables for database settings inside the server config block
B. Define nested classes for ServerConfig and DatabaseConfig, then use nested receiver blocks
C. Pass database settings as strings to the server config block without nesting
D. Create separate functions for server and database config without nesting
Solution
Step 1: Understand nested configuration needs
To configure server and database settings clearly, nested blocks with receivers allow intuitive setup.
Step 2: Use nested classes and receiver blocks
Define ServerConfig with a DatabaseConfig property and provide a nested block to configure database inside server block.
Step 3: Why other options are less suitable
Global variables reduce clarity, passing strings loses structure, separate functions lose nesting benefits.
Final Answer:
Define nested classes for ServerConfig and DatabaseConfig, then use nested receiver blocks -> Option B
Quick Check:
Nested classes + blocks = Define nested classes for ServerConfig and DatabaseConfig, then use nested receiver blocks [OK]
Hint: Use nested classes and blocks for clear hierarchical config [OK]
Common Mistakes:
Using global variables instead of nested blocks
Passing unstructured strings for nested config
Avoiding nested blocks reduces readability
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.