Start learning free

LESSON 67 OF 70 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in Scala: LineItem and Cart Classes

Practice Read the full explanation

A shop keeps its orders in a cart. Build two classes that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.

LineItem

  • class LineItem(val name: String, val price: Double, val quantity: Int): the primary constructor declares the three fields.
  • def subtotal(): Double returns price * quantity.

Cart

  • It keeps its items in private val items = scala.collection.mutable.ArrayBuffer[LineItem]().
  • def add(item: LineItem): Unit appends the item to the buffer.
  • def total(): Double returns the sum of the subtotals of all items: start var sum = 0.0, loop with for (item <- items), return sum.

Rules:

  • The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
  • An empty cart has a total of 0.
  • An item with price 5 and quantity 3 has a subtotal of 15.
  • Prices in the driver are whole numbers.

The driver lives in Solution.mainFunction() and uses .toInt to print whole numbers.

The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:

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)
    }
}

Expected output:

Empty: 0
Subtotal: 15
Total: 75
Total: 95

Write LineItem with its primary constructor first, then Cart.

for (item <- items) { sum += item.subtotal() }

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)
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    SCALA · PROJECTS: OBJECT-ORIENTED

    Shopping Cart in Scala, explained

    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 method subtotal(): Double that returns price * quantity.
    • Cart keeps its rows in a private ArrayBuffer[LineItem]. add(item: LineItem): Unit appends a row, and total(): Double returns 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

    1. Declare LineItem with three val parameters in the class line: name, price and quantity. A parameter marked val becomes a public read-only field automatically, so there is no constructor body and no assignments.
    2. Add subtotal with a Double result.
    3. Return price * quantity. The Int quantity is widened to Double in the multiplication, so the result is a Double.
    4. Declare Cart below LineItem: it will hold many rows.
    5. Add private val items set to an empty scala.collection.mutable.ArrayBuffer[LineItem](). It is a val because the buffer's contents change, not the variable itself. Private keeps outside code from editing the rows directly.
    6. Write the header of add, taking a LineItem named item and returning Unit.
    7. Append the item with items.append(item). The buffer keeps the rows in the order they came in.
    8. Write the header of total, returning a Double.
    9. Start var sum = 0.0. It is a var because it grows as rows are added, and starting at zero is what makes an empty cart total 0.
    10. Loop with for (item <- items). The arrow reads "item comes from items": the loop body runs once per row, with item set to that row.
    11. Add item.subtotal() to sum. Each row knows its own price and quantity.
    12. Return sum after 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

    • val in a class parameter list. class LineItem(val name: String, ...) creates a field and a getter. Without val, a parameter used only in the constructor stays private to the class. With a plain parameter name: String, reading x.name from outside is a compile error, reported as "private value name can only be accessed from class". The driver never reads the fields, but val is what the lesson asks for.
    • The for loop. for (item <- items) works on any collection and needs no index. It is Scala's counterpart of a for-each loop.
    • += on a var. sum += item.subtotal() is shorthand for sum = sum + item.subtotal().
    • Double output. println(cart.total()) would print 75.0. The driver calls .toInt to print 75.
    • append and += do the same job on an ArrayBuffer; the lesson uses append.

    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 sum stays at 0.0, so total() returns 0.0. This is why the starting value is zero and not something else.
    • Using val for sum. A val can't be reassigned, so sum += ... doesn't compile. It has to be a var.
    • return inside the loop. Returning sum inside the for body ends the method after the first row. The return sum belongs after the closing brace of the loop.
    • Same row added twice. Adding the same LineItem object 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 of 0.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 a Long.

    Testing

    Try a few small carts:

    • A new cart: total() gives 0.
    • One row LineItem("Pen", 2.0, 4): subtotal() and the cart's total() 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.
    • val in a class parameter list turns the parameter into a field.
    • Computing the total on demand means it always matches the rows in the cart.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free