Problem overview
You build two classes that work together. A LineItem is one row of an order: a product name, a unit price and a quantity. A Cart holds many rows and adds them up.
LineItem(val name: String, val price: Double, val quantity: Int)has a methodsubtotal(): Doublethat returnsprice * quantity.Cartkeeps its rows in a privateArrayBuffer[LineItem].add(item: LineItem): Unitappends a row, andtotal(): Doublereturns the sum of all subtotals.
The driver checks an empty cart (total 0) and an apple row of price 5 and quantity 3 (subtotal 15). It then adds the apple and a bread row of price 20 and quantity 3, giving a total of 5 * 3 + 20 * 3 = 75. After a milk row of price 10 and quantity 2 is added, the next total is 95. The output is:
Empty: 0
Subtotal: 15
Total: 75
Total: 95
Approach: composition and computing on demand
The cart has line items; it is not one. That relationship is called composition: Cart stores LineItem objects and asks each one for its own subtotal. The cart doesn't need to know how a row computes its cost, only that it can report it. If the subtotal rule changed later, say with a discount, only LineItem would change.
The total is not stored. Each call to total() adds up the rows the cart holds at that moment, so there is no second number to keep in sync. Adding a row after one call to total() changes the result of the next call, which is exactly what the last two driver lines show.
Step by step
- Declare
LineItemwith threevalparameters in the class line:name,priceandquantity. A parameter markedvalbecomes a public read-only field automatically, so there is no constructor body and no assignments. - Add
subtotalwith aDoubleresult. - Return
price * quantity. TheIntquantity is widened toDoublein the multiplication, so the result is aDouble. - Declare
CartbelowLineItem: it will hold many rows. - Add
private val itemsset to an emptyscala.collection.mutable.ArrayBuffer[LineItem](). It is avalbecause the buffer's contents change, not the variable itself. Private keeps outside code from editing the rows directly. - Write the header of
add, taking aLineItemnameditemand returningUnit. - Append the item with
items.append(item). The buffer keeps the rows in the order they came in. - Write the header of
total, returning aDouble. - Start
var sum = 0.0. It is avarbecause it grows as rows are added, and starting at zero is what makes an empty cart total 0. - Loop with
for (item <- items). The arrow reads "item comes from items": the loop body runs once per row, withitemset to that row. - Add
item.subtotal()tosum. Each row knows its own price and quantity. - Return
sumafter the loop. It sits outside the loop braces, so it runs once, after every row has been added.
The solution in Scala
class LineItem(val name: String, val price: Double, val quantity: Int) {
def subtotal(): Double = {
return price * quantity
}
}
class Cart {
private val items = scala.collection.mutable.ArrayBuffer[LineItem]()
def add(item: LineItem): Unit = {
items.append(item)
}
def total(): Double = {
var sum = 0.0
for (item <- items) {
sum += item.subtotal()
}
return sum
}
}
class Solution {
def mainFunction(): Unit = {
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)
}
}
Scala details
valin a class parameter list.class LineItem(val name: String, ...)creates a field and a getter. Withoutval, a parameter used only in the constructor stays private to the class. With a plain parametername: String, readingx.namefrom outside is a compile error, reported as "private value name can only be accessed from class". The driver never reads the fields, butvalis what the lesson asks for.- The
forloop.for (item <- items)works on any collection and needs no index. It is Scala's counterpart of a for-each loop. +=on avar.sum += item.subtotal()is shorthand forsum = sum + item.subtotal().Doubleoutput.println(cart.total())would print75.0. The driver calls.toIntto print75.appendand+=do the same job on anArrayBuffer; the lesson usesappend.
Complexity
add is amortised O(1), because appending to the end of an ArrayBuffer is cheap on average. subtotal is O(1). total visits every row once, so it takes O(n) time for n rows and O(1) extra space. The cart itself uses O(n) space.
The cost of recomputing on every call is the price of never having a stale total. If totals were requested constantly on a huge cart, you could keep a running sum updated in add instead, at the cost of keeping two things consistent.
Edge cases and common mistakes
- Empty cart. The loop doesn't run, and
sumstays at 0.0, sototal()returns0.0. This is why the starting value is zero and not something else. - Using
valforsum. Avalcan't be reassigned, sosum += ...doesn't compile. It has to be avar. returninside the loop. Returningsuminside theforbody ends the method after the first row. Thereturn sumbelongs after the closing brace of the loop.- Same row added twice. Adding the same
LineItemobject twice counts it twice: the buffer holds two references to one row, and both contribute. With the apple row (subtotal 15) added twice, the total is 30. - Floating-point sums. Prices are
Double, which can't represent most decimals exactly. A row with price 0.1 and quantity 3 has a subtotal of0.30000000000000004. The lesson uses whole prices, so the totals are exact here, but money handling in general usually needs a different approach, such as counting cents in aLong.
Testing
Try a few small carts:
- A new cart:
total()gives 0. - One row
LineItem("Pen", 2.0, 4):subtotal()and the cart'stotal()both give 8. - Add a second row
LineItem("Ink", 3.0, 1): the total becomes 11. - A row with quantity 0: its subtotal is 0, so the total doesn't change.
Key takeaways
- Composition: a cart has line items, so it stores them and delegates the subtotal to each one.
valin a class parameter list turns the parameter into a field.- Computing the total on demand means it always matches the rows in the cart.
