0
0
Kotlinprogramming~30 mins

Infix functions in DSLs in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Infix Functions in Kotlin DSLs
📖 Scenario: Imagine you are creating a small Kotlin program to build a simple shopping list using a Domain Specific Language (DSL). You want to use infix functions to make the code easy to read and write, like a natural language.
🎯 Goal: Build a Kotlin program that uses infix functions to add items with quantities to a shopping list in a clear and readable way.
📋 What You'll Learn
Create a data class called Item with name and quantity properties
Create an infix function called qty to set the quantity of an item
Create a list called shoppingList to hold Item objects
Add items to the shoppingList using the infix qty function
Print the shopping list with item names and quantities
💡 Why This Matters
🌍 Real World
Infix functions help make Kotlin DSLs more readable and expressive, useful for configuration files, build scripts, and custom mini-languages.
💼 Career
Understanding infix functions and DSLs is valuable for Kotlin developers working on clean APIs, build tools like Gradle, or domain-specific applications.
Progress0 / 4 steps
1
Create the Item data class
Create a Kotlin data class called Item with two properties: name of type String and quantity of type Int.
Kotlin
Need a hint?

Use data class Item(val name: String, val quantity: Int) to define the class.

2
Create the infix function qty
Create an infix function called qty that extends String. It should take an Int parameter called amount and return an Item with the string as the name and amount as the quantity.
Kotlin
Need a hint?

Define the infix function with infix fun String.qty(amount: Int): Item and return Item(this, amount).

3
Create the shoppingList and add items
Create a mutable list called shoppingList of type Item. Add these items using the infix qty function: "Apples" qty 5, "Bananas" qty 3, and "Carrots" qty 7.
Kotlin
Need a hint?

Use mutableListOf() to create the list and add items with shoppingList.add("Apples" qty 5).

4
Print the shopping list
Use a for loop with variables item to iterate over shoppingList. Print each item's name and quantity in the format: "Apples: 5".
Kotlin
Need a hint?

Use for (item in shoppingList) and println("${item.name}: ${item.quantity}") to print each item.