Start learning free

LESSON 191 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V3 in Scala: Free Shipping with if/else

Practice Read the full explanation

Use an if/else to decide whether to charge shipping based on a free-shipping threshold.

You start with:

        val subtotal = 75
        val shippingCost = 10
        val freeShippingThreshold = 100

Build:

Subtotal: $75
Shipping: $10
Total: $85

Rules:

  • If subtotal >= freeShippingThreshold, set shipping to 0; otherwise set it to shippingCost.
  • total = subtotal + shipping.
  • Always include all three lines (Subtotal, Shipping, Total). When shipping is free, the line shows $0: for a subtotal of 120 the lines would be Subtotal: $120, Shipping: $0, Total: $120.
  • Join the three lines with a newline "\n" into one string result, then print it with println(result).

Decide shipping in an if/else first, then build the three lines.

Declare var shipping = 0 before the if, so it is still visible after the if/else, then assign it in both branches.

In Scala "Total: $" + total converts the number to text for you.

        val subtotal = 75
        val shippingCost = 10
        val freeShippingThreshold = 100

        var shipping = 0
        if (subtotal >= freeShippingThreshold) {
            shipping = 0
        } else {
            shipping = shippingCost
        }
        val total = subtotal + shipping
        val line1 = "Subtotal: $" + subtotal
        val line2 = "Shipping: $" + shipping
        val line3 = "Total: $" + total
        val result = line1 + "\n" + line2 + "\n" + line3
        println(result)

STEP 1 OF 11
    Ctrl + Enter to check

    SCALA · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V3 in Scala, explained

    Problem overview

    This version of the shopping cart program adds a rule: orders at or above a threshold ship for free. You start with three values, subtotal (75), shippingCost (10) and freeShippingThreshold (100). The program decides what shipping the order pays, adds it to the subtotal, and prints a three-line receipt as one string.

    For the starting values the cart is under the threshold, so it pays the regular shipping:

    Subtotal: $75
    Shipping: $10
    Total: $85

    With a subtotal of 120 the cart ships free, but the Shipping line still appears, showing $0, so the receipt always has the same three lines.

    Approach: decide the shipping first, then build the text

    The only decision in the program is the shipping amount, so make it first and keep the rest straight-line code. If subtotal >= freeShippingThreshold, shipping is 0. Otherwise it is shippingCost. Everything after that, the total and the three lines, is the same for both cases.

    The comparison is >=, not >: a cart that lands exactly on the threshold qualifies. The program does not need a special case for it, because the operator already covers it.

    Step by step

    1. Declare shipping as a var starting at 0. It has to exist before the if so that the code after the if can still see it, and it is a var because the branches assign to it.
    2. Write the if on the threshold, with its closing brace right away, so the block is never left open while you add the body.
    3. Free case: inside the if, set shipping to 0.
    4. Close the if block, write else and open its block. In this style the else sits on the same line as the closing brace.
    5. Paid case: inside the else, set shipping to shippingCost.
    6. Compute total as subtotal + shipping. This works in both cases, because free shipping is just a shipping of 0.
    7. Build line1, line2 and line3, each a label followed by a number.
    8. Join the lines into result with "\n" between each two, so there are two newlines for three lines.
    9. Print result with println.

    The solution in Scala

            val subtotal = 75
            val shippingCost = 10
            val freeShippingThreshold = 100
    
            var shipping = 0
            if (subtotal >= freeShippingThreshold) {
                shipping = 0
            } else {
                shipping = shippingCost
            }
            val total = subtotal + shipping
            val line1 = "Subtotal: $" + subtotal
            val line2 = "Shipping: $" + shipping
            val line3 = "Total: $" + total
            val result = line1 + "\n" + line2 + "\n" + line3
            println(result)

    A few details are worth knowing.

    • The var and the branches. The if here is used as a statement: each branch assigns to shipping. A val would reject the second assignment, so var is required in this form.
    • "Subtotal: $" + subtotal joins a String and an Int. Scala converts the number to text when it is added to a string, and the $ is an ordinary character in a normal string literal. Only in an interpolated string such as s"..." does $ start a variable, and a literal dollar sign there is written $$.
    • Integers only. All values are Int, so the receipt shows whole dollars with no decimals.

    In Scala an if/else is also an expression that gives a value, so val shipping = if (subtotal >= freeShippingThreshold) 0 else shippingCost would replace the var and both assignments. This lesson uses the statement form because that is how the step-by-step build works, and it makes each branch easy to see.

    Edge cases and common mistakes

    • Exactly on the threshold. A subtotal of 100 ships free, because of >=. Using > would charge 10 for it.
    • Dropping the free-shipping line. The receipt keeps all three lines for a free order. The shipping line reads Shipping: $0.
    • Declaring shipping inside a branch. A name created inside { ... } is not visible after the closing brace, so the total could not use it.
    • Hard-coding the numbers. The threshold and cost are named values, so the rule lives in one line each. Writing 100 or 10 inside the if would work for this input but break as soon as the starting values change.
    • Using = as a comparison. A single = assigns, and an assignment is not a Boolean, so the compiler rejects it as a condition. Comparison needs >=, == and friends.
    • A newline after the last line. Two separators join three lines. A third newline would add a blank line at the end.

    Following both paths

    The program has two paths, and only one of them runs each time. With subtotal = 120 the condition 120 >= 100 is true, so the if block runs, shipping becomes 0, and the else block is skipped entirely. total is then 120 + 0. The output is:

    Subtotal: $120
    Shipping: $0
    Total: $120

    With subtotal = 99 the condition is false, so the else block runs instead and shipping becomes shippingCost. The result is a total of 109. Because the three lines are built after the if/else, they never need to know which path was taken: they just read the final value of shipping.

    That is the main idea of the lesson. A decision should be made once, in one place, and the code after it should use the outcome without repeating the test.

    Testing

    Try these in the editor above by changing subtotal:

    SubtotalShippingTotal
    75$10$85
    99$10$109
    100$0$100
    120$0$120

    The next version builds on this receipt.

    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free