Adding items
- Kotlin course
- Beginner
- Lesson 49/116
- 6 min
Learn to add items with the addItem function.
Adding items (add)
cart.add(...) adds a product to the cart. Each call puts one item at the end of the list.
val cart = mutableListOf<Product>()
cart.add(Product("Apple", 5.0))
cart.add(Product("Bread", 3.0))
println(cart.size) // 2After two items, cart.size is 2. mutableListOf is a dynamic list; you don't need to know the item count in advance.
Product("Apple", 5.0) creates a new Product instance and adds it to the list.
The cart.size property
cart.size gives the number of items in the cart. For an empty cart it returns 0.
val cart = mutableListOf<Product>()
println(cart.size) // 0
cart.add(Product("Apple", 5.0))
println(cart.size) // 1Each add call increases the size by one. size is a property; no parentheses needed.
The size grows with each item you add; there is no fixed limit.
Practice Add two items and print the size
Add two items to the cart from the previous lesson. Add cart.add(Product("Apple", 5.0)) and cart.add(Product("Bread", 3.0)) before println(cart.size). The size should be 2.
Starter code
data class Product(val name: String, val price: Double)
fun main() {
val cart = mutableListOf<Product>()
// Add two products here
println(cart.size)
}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))
println(cart.size)
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the list methods
| Term | Meaning |
|---|---|
cart.add(item) |
Add an item |
cart.size |
Item count |
mutableListOf |
Empty list |
Product(...) |
New product |
2 What does cart.add(Product("Apple", 5.0)) do?
- Removes Apple from the cart
- Shows Apple
- Empties the cart
- Adds Apple to the cart Correct answer
Explanation: add puts a new Product in the list.
3 Complete the add call
cart.____(Product("Apple", 5.0))
cart.add(Product("Apple", 5.0))
Explanation: cart.add(Product(...)) adds a product to the cart.