Start learning free

LESSON 67 OF 70 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in Kotlin: 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.
  • fun subtotal(): Double returns price * quantity.

Cart

  • It keeps its items in private val items = mutableListOf<LineItem>().
  • fun add(item: LineItem) appends the item to the list.
  • fun total(): Double returns the sum of the subtotals of all items: start var sum = 0.0, loop with for (item in 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 {
    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())
    }
}

Expected output:

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

Write LineItem with its primary constructor first, then Cart.

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

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

STEP 1 OF 12
    Ctrl + Enter to check

    KOTLIN · PROJECTS: OBJECT-ORIENTED

    Shopping Cart in Kotlin, explained

    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. Its subtotal() returns price * quantity.
    • Cart holds many rows in a private mutableListOf<LineItem>(). add(item) appends a row, and total() 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

    1. Declare LineItem with its three values in the class header as val parameters. Marking a parameter val makes it a property, so there is no constructor body and no assignment.
    2. Start subtotal, a method returning a Double.
    3. Return price * quantity. Both are properties of the row.
    4. Declare Cart, below LineItem.
    5. Add the list: private val items = mutableListOf<LineItem>(). It is a val because the list's contents change and the list itself is never replaced.
    6. Start add, taking a LineItem named item. It returns nothing.
    7. Append with items.add(item). Rows stay in the order they arrived.
    8. Start total, returning a Double.
    9. Create var sum = 0.0. It is a var because it grows as rows are added. Starting at zero is what gives an empty cart a total of 0.
    10. Loop with for (item in items). The loop hands you each row itself, so no index is needed.
    11. Add each row's subtotal to sum by calling item.subtotal().
    12. Return sum after 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 * quantity multiplies a Double by an Int. Kotlin allows that and the result is a Double, which matches the declared return type.
    • Double literals. The price must be a Double, so the driver writes 5.0. LineItem("Apple", 5, 3) does not compile: the compiler reports that the actual type is Int but Double was expected.
    • Printing doubles. A Double prints with a decimal point, so the total of the second cart prints as 95.0. The driver calls .toInt() to print 95.
    • Properties from the header. Because name, price and quantity are vals, code outside the class can read them (apple.name gives Apple) but not assign to them.
    • Private list. Outside code cannot touch items. The only way to change the cart is add, and the only way to read it is total.

    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 sum is 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 sum inside 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. A val cannot be reassigned, so sum += ... would not compile. Use var.
    • 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.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free