Putting it together
- Kotlin course
- Beginner
- Lesson 52/116
- 6 min
Combine the cart functions with a menu loop.
Putting it together
In the final lesson we combine all pieces: adding items, listing and printing the total. This is the core of a full cart app.
// Add
cart.add(Product("Apple", 5.0))
cart.add(Product("Bread", 3.0))
// List
for (item in cart) {
println("${item.name}: ${item.price}")
}
// Total
val total = cart.sumOf { it.price }
println("Total: $total")The output has two parts: the item list and the total. This structure is the core of a real store cart.
Practice Print the total
Add println("Total: $total") after the for loop in the previous cart (two items + for loop). The output: the item list and "Total: 8.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 }
for (item in cart) {
println("${item.name}: ${item.price}")
}
// Print the total
}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}")
}
println("Total: $total")
}Expected output
Apple: 5.0 Bread: 3.0 Total: 8.0
Project complete
Congratulations! You wrote the core of a shopping cart app. You learned:
- data classes with
data class Product - mutable lists with
mutableListOf - adding items with
cart.add - summing prices with
sumOf - listing items with
for
By combining these, you built the add, list and total logic. Later you can extend the cart with tax, discounts and quantities.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the integration steps
| Term | Meaning |
|---|---|
cart.add |
Add item |
for (item in cart) |
List |
sumOf |
Total |
println("Total: ...") |
Print total |
2 What does the final version of this project produce?
- Only the item list
- Only the total
- The item list and the total Correct answer
- Empty output
Explanation: The cart prints both the item list and the total.
3 Complete the total print template
println("____: $total")
println("Total: $total")
Explanation: println("Total: $total") prints the total.