Listing the cart
- Kotlin course
- Beginner
- Lesson 51/116
- 6 min
Write the function that prints the cart formatted.
Listing the cart
To print the items in the cart, use a for loop. Each item is a Product; its fields are accessed with item.name and item.price.
for (item in cart) {
println("${item.name}: ${item.price}")
}
// Apple: 5.0
// Bread: 3.0Each loop step, item represents one product. The template ${item.name} embeds the name, ${item.price} the price.
This format is handy for showing the cart to the user.
Practice List the items
Add a for (item in cart) { println("${item.name}: ${item.price}") } loop to the previous cart (two items + total). Each item should be on its own line: "Apple: 5.0" and "Bread: 3.0".
Starter code
data class Product(val name: String, val price: Double)
fun main() {
val cart = mutableListOf<Product>()
cart.add(Product("Apple", 5.0))
cart.add(Product("Bread", 3.0))
val total = cart.sumOf { it.price }
// List the items
}Sample solution
data class Product(val name: String, val price: Double)
fun main() {
val cart = mutableListOf<Product>()
cart.add(Product("Apple", 5.0))
cart.add(Product("Bread", 3.0))
val total = cart.sumOf { it.price }
for (item in cart) {
println("${item.name}: ${item.price}")
}
}Expected output
Apple: 5.0 Bread: 3.0
Formatted output
To make the output more readable, templates and formatting are used. ${item.name}: ${item.price} shows each item on one line.
// Output:
// Apple: 5.0
// Bread: 3.0A colon and space separate the name and price. Without templates you'd write item.name + ": " + item.price; templates are shorter.
Each item is on its own line; println adds the line break automatically.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is used to print every item in the cart?
- if statement
- for loop Correct answer
- when statement
- println alone
Explanation: A for loop visits each item in the list in turn.
2 Complete the for loop
for (____ in cart) { println("${item.name}: ${item.price}") }
for (item in cart) { println("${item.name}: ${item.price}") }
Explanation: for (item in cart) takes each product in turn.
3 Match the listing concepts
| Term | Meaning |
|---|---|
for (item in cart) |
List loop |
item.name |
Item name |
item.price |
Item price |
${item.name} |
Template |