Start learning free

LESSON 193 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 in Scala: Coupon Codes with a Map

Practice Read the full explanation

Use a map as a fast lookup table for coupon discounts.

You start with:

        val subtotal = 100
        val coupon = "SAVE20"
        val coupons = scala.collection.mutable.Map("SAVE10" -> 10, "SAVE20" -> 20, "SAVE50" -> 50)

Build:

Total: $80

Rules:

  • Look up coupon in coupons. If it is there, its value is the discount; if it is not (an unknown code), the discount is 0.
  • total = subtotal - discount.
  • Build the text "Total: $<total>" (e.g. "Total: $80"; an unknown coupon would give "Total: $100").
  • Store it in result, then print it with println(result).

Use coupons.getOrElse(coupon, 0): it returns the value if the key is present, or 0 if it is missing.

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

        val subtotal = 100
        val coupon = "SAVE20"
        val coupons = scala.collection.mutable.Map("SAVE10" -> 10, "SAVE20" -> 20, "SAVE50" -> 50)

        val discount = coupons.getOrElse(coupon, 0)
        val total = subtotal - discount
        val result = "Total: $" + total
        println(result)

STEP 1 OF 4
    Ctrl + Enter to check

    SCALA · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V5 in Scala, explained

    Problem overview

    The cart now accepts a coupon code. The program starts with a subtotal of 100, the shopper's coupon text, "SAVE20", and a mutable map coupons from each valid code to the amount it takes off: SAVE10 is 10, SAVE20 is 20 and SAVE50 is 50. It looks the coupon up, subtracts the discount and prints one line:

    Total: $80

    A code that is not in the map takes nothing off. With a coupon of "FREE" and the same subtotal the line is Total: $100.

    Approach: a map as a lookup table

    A map stores pairs of a key and a value, and finds the value for a key directly, without scanning. Here the keys are coupon codes and the values are discounts. The alternative is a chain of if and else if tests, one per code, which grows with every new coupon and has to be edited each time. With a map, adding a coupon is adding one pair to the data, and the logic does not change.

    The one subtle part is the unknown code. A shopper can type anything, so a missing key is a normal case, and it must mean a discount of 0. Scala has a method for exactly this: getOrElse(key, default) returns the value stored for the key, or the default when the key is absent.

    Step by step

    1. Look up the discount. Create val discount from coupons.getOrElse(coupon, 0). The result is an Int either way: the stored discount, or 0.
    2. Compute total as the subtotal minus the discount.
    3. Build result as "Total: $" followed by the total. The + converts the Int to text when it is added to a string.
    4. Print result with println.

    The solution in Scala

            val subtotal = 100
            val coupon = "SAVE20"
            val coupons = scala.collection.mutable.Map("SAVE10" -> 10, "SAVE20" -> 20, "SAVE50" -> 50)
    
            val discount = coupons.getOrElse(coupon, 0)
            val total = subtotal - discount
            val result = "Total: $" + total
            println(result)

    The language details to know:

    • scala.collection.mutable.Map. Scala's default Map is immutable. The starter uses the mutable one, written with its full name, so pairs can be added and changed later. This lesson only reads from it. The pairs are written with "SAVE10" -> 10, and the map's type, Map[String, Int], is inferred.
    • Three ways to read a key. coupons("SAVE20") returns 20, but coupons("FREE") throws a java.util.NoSuchElementException with the message key not found: FREE. coupons.get("FREE") returns an Option: None for a missing key and Some(10) for "SAVE10". getOrElse unwraps that choice in one call by supplying the fallback.
    • Keys are compared by value. Two strings with the same characters are the same key, so the variable coupon finds the entry whether or not it is the same object as the literal in the map.

    Edge cases and common mistakes

    • Calling coupons(coupon) directly. It works for every known code and then crashes on the first unknown one. This is the most common mistake in this lesson, and the reason the step uses getOrElse.
    • Case matters. The key is the exact text, so "save20" is not "SAVE20". With the lowercase code, getOrElse returns 0 and the line is Total: $100. Converting the code with toUpperCase before the lookup would be a reasonable addition, but this lesson compares the text as given.
    • Discounts larger than the subtotal. The program subtracts blindly. With a subtotal of 30 and SAVE50 the printed line is Total: $-20. Nothing in this lesson clamps the total at zero.
    • An empty coupon. An empty string is just another missing key, so the discount is 0.

    Testing

    Try these in the editor above by changing subtotal and coupon:

    SubtotalCouponOutput
    100SAVE20Total: $80
    100save20Total: $100
    100FREETotal: $100
    30SAVE50Total: $-20

    The lookup-with-a-default pattern, getOrElse on a map, is the same one counting problems use to start a counter at 0 for a key that has not been seen yet. The next version builds on it.

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