0
0
Kotlinprogramming~30 mins

Configuration DSL pattern in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Build a Simple Configuration DSL in Kotlin
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use println("Coffee type: ${myCoffee.type}, Size: ${myCoffee.size}, Sugar: ${myCoffee.sugar}") to print the configuration.