Problem overview
A cart is made of rows, and each row is a product with a price and a quantity. The lesson asks for two classes that work together:
LineItem(val name: String, val price: Double, val quantity: Int)is one row. Itssubtotal()returnsprice * quantity.Cartholds many rows in a privatemutableListOf<LineItem>().add(item)appends a row, andtotal()returns the sum of all the subtotals.
The driver checks an empty cart (total 0), then an Apple row of 5 each times 3, which has subtotal 15. It puts the apple and 3 loaves of bread at 20 each into a cart, so the total is 15 + 60 = 75. It then adds 2 bottles of milk at 10 each, and the next total is 95:
Empty: 0
Subtotal: 15
Total: 75
Total: 95
Approach
The relationship between the classes is composition. A cart has line items; it is not a line item. So Cart does not extend LineItem. It keeps a list of them.
The work is split by who knows what. A LineItem knows its own price and quantity, so it computes its own subtotal. The Cart does not look at prices at all: it asks each row for its subtotal and adds the answers together.
The total is not stored. total() works it out from the rows in the cart at the moment it is called, so the third line of output (75) and the fourth (95) differ only because a row was added between them. There is no running total to keep in step with the list.
Step by step
- Declare
LineItemwith its three values in the class header asvalparameters. Marking a parametervalmakes it a property, so there is no constructor body and no assignment. - Start
subtotal, a method returning aDouble. - Return
price * quantity. Both are properties of the row. - Declare
Cart, belowLineItem. - Add the list:
private val items = mutableListOf<LineItem>(). It is avalbecause the list's contents change and the list itself is never replaced. - Start
add, taking aLineItemnameditem. It returns nothing. - Append with
items.add(item). Rows stay in the order they arrived. - Start
total, returning aDouble. - Create
var sum = 0.0. It is avarbecause it grows as rows are added. Starting at zero is what gives an empty cart a total of 0. - Loop with
for (item in items). The loop hands you each row itself, so no index is needed. - Add each row's subtotal to
sumby callingitem.subtotal(). - Return
sumafter the loop, outside its braces, so it runs once all rows have been added.
The solution in Kotlin
class LineItem(val name: String, val price: Double, val quantity: Int) {
fun subtotal(): Double {
return price * quantity
}
}
class Cart {
private val items = mutableListOf<LineItem>()
fun add(item: LineItem) {
items.add(item)
}
fun total(): Double {
var sum = 0.0
for (item in items) {
sum += item.subtotal()
}
return sum
}
}
class Solution {
fun mainFunction() {
val empty = Cart()
println("Empty: " + empty.total().toInt())
val apple = LineItem("Apple", 5.0, 3)
println("Subtotal: " + apple.subtotal().toInt())
val cart = Cart()
cart.add(apple)
cart.add(LineItem("Bread", 20.0, 3))
println("Total: " + cart.total().toInt())
cart.add(LineItem("Milk", 10.0, 2))
println("Total: " + cart.total().toInt())
}
}
Kotlin details
- Mixed arithmetic.
price * quantitymultiplies aDoubleby anInt. Kotlin allows that and the result is aDouble, which matches the declared return type. - Double literals. The price must be a
Double, so the driver writes5.0.LineItem("Apple", 5, 3)does not compile: the compiler reports that the actual type isIntbutDoublewas expected. - Printing doubles. A
Doubleprints with a decimal point, so the total of the second cart prints as95.0. The driver calls.toInt()to print95. - Properties from the header. Because
name,priceandquantityarevals, code outside the class can read them (apple.namegivesApple) but not assign to them. - Private list. Outside code cannot touch
items. The only way to change the cart isadd, and the only way to read it istotal.
Complexity
subtotal and add are O(1) on average. total visits each row once, so it is O(n) for n rows. Because the total is recomputed on every call, asking for it twice costs two passes. The cart uses O(n) space for its rows.
Edge cases and common mistakes
- Empty cart. The loop does not run, and
sumis still 0.0, so the total is 0. - Adding later. A row added after a
total()call shows up in the next one. That is why the total is computed on demand and not saved. - Return inside the loop. Putting
return suminside the braces would stop after the first row. The cart in the driver would give 15 instead of 75. - Resetting
sum. Declare it before the loop, not inside it, or each pass starts again from zero. val sum. Avalcannot be reassigned, sosum += ...would not compile. Usevar.- Fractional prices. The driver uses whole prices, but doubles can show tiny rounding noise. A single row of price 0.1 and quantity 3 has a subtotal of
0.30000000000000004. Calling.toInt()on such a total drops the whole fractional part, not just the noise, so it suits only whole-number prices.
