Cart design
- Kotlin course
- Beginner
- Lesson 48/116
- 6 min
Design the data class structure for the shopping cart.
Project: Shopping cart
In this 5-lesson project you'll build a shopping cart. Each lesson adds one piece, and by the final lesson you'll have a complete app.
You'll use what you learned before:
- data classes with
data class - mutable lists with
mutableListOf - iteration with
for - output with
println
You'll add items, calculate totals and list the cart step by step. Ready? Let's start.
data class Product
To represent a product, Kotlin uses data class. This is a shorthand for data-holding classes; you'll see the details later.
data class Product(val name: String, val price: Double)This single line creates a class with name and price fields. data class auto-generates toString, equals and more.
To hold products, create an empty list with mutableListOf<Product>(); this will also be covered in detail later.
Practice Define the empty cart
Define a data class Product(val name: String, val price: Double). In fun main(), create an empty cart with val cart = mutableListOf<Product>() and print its size with println(cart.size).
Starter code
data class Product(val name: String, val price: Double)
fun main() {
// Print the cart size
}Sample solution
data class Product(val name: String, val price: Double)
fun main() {
val cart = mutableListOf<Product>()
println(cart.size)
}Expected output
0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a shopping cart need first?
- A database
- A class
- A list to hold items Correct answer
- A file
Explanation: A cart uses a list to hold items.
2 Complete the data class definition
data ____ Product(val name: String, val price: Double)
data class Product(val name: String, val price: Double)
Explanation: data class Product(...) defines a data class.
3 Match the cart concepts
| Term | Meaning |
|---|---|
data class |
Data class |
mutableListOf |
Create list |
Product |
Product class |
cart.size |
Item count |