Start learning free

LESSON 193 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 in Kotlin: 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 = mutableMapOf("SAVE10" to 10, "SAVE20" to 20, "SAVE50" to 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.getOrDefault(coupon, 0): it returns the value if the key is present, or 0 if it is missing.

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

        val subtotal = 100
        val coupon = "SAVE20"
        val coupons = mutableMapOf("SAVE10" to 10, "SAVE20" to 20, "SAVE50" to 50)

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

STEP 1 OF 4
    Ctrl + Enter to check

    KOTLIN · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V5 in Kotlin, explained

    Problem overview

    This version applies a coupon to an order. The program starts with a subtotal of 100, the coupon the shopper typed, "SAVE20", and a map coupons from each valid code to the amount it takes off: SAVE10 is 10, SAVE20 is 20 and SAVE50 is 50.

    The program looks the typed code up in the map. If the code is there, its value is the discount. If it isn't, the discount is 0. The total is the subtotal minus the discount, printed as a single line. For the starting values:

    Total: $80

    With a code the map doesn't know, such as SAVE99, the same program prints Total: $100: the shopper typed something, and it simply takes nothing off.

    Approach: a map as a lookup table

    You could answer "which discount does this code give?" with a chain of if statements, one per code. That works for three coupons and gets unwieldy for three hundred, and every new coupon means new code. A map keeps the data separate from the logic: the codes and amounts live in one place, and the lookup is a single call that doesn't change when the table grows.

    The one subtle part is the missing key. A shopper can type any text, so the lookup has to have a plan for codes that aren't in the table. The plan here is a default: ask the map for the code, and say what to use if it isn't found.

    Step by step

    1. Look up the discount. Create discount with coupons.getOrDefault(coupon, 0). The call returns the value stored for the key, or its second argument, 0, when the key is absent.
    2. Compute total. It is the subtotal minus the discount. With no discount it equals the subtotal.
    3. Build result. It is the text Total: $ followed by the total. The label is the same for every order, only the number changes.
    4. Print result with println.

    The solution in Kotlin

            val subtotal = 100
            val coupon = "SAVE20"
            val coupons = mutableMapOf("SAVE10" to 10, "SAVE20" to 20, "SAVE50" to 50)
    
            val discount = coupons.getOrDefault(coupon, 0)
            val total = subtotal - discount
            val result = "Total: $" + total
            println(result)
    

    Kotlin details worth a closer look:

    • Building the map. "SAVE10" to 10 creates a pair, and mutableMapOf collects pairs into a MutableMap<String, Int>. Kotlin infers both types from the pairs. A plain mapOf would make a read-only view; this lesson's starter uses the mutable one, although the solution never changes it.
    • Missing keys. The indexing form coupons[coupon] returns Int?, which is null for a code that isn't in the map. That nullable value can't be used in subtotal - ... until you deal with the null. getOrDefault avoids the problem by returning a plain Int. The idiomatic Kotlin alternative is coupons[coupon] ?: 0, where ?: supplies the fallback for null.
    • Case matters. Map keys are compared with equals, so "save20" and "SAVE20" are different keys. The lookup for save20 finds nothing and uses 0.
    • The dollar sign. In "Total: $" the $ is followed by the closing quote, so it is an ordinary character. "Total: $total" would not work here: it would insert the number and drop the dollar sign.

    Complexity

    A map lookup takes constant time on average, no matter how many coupons the table holds, so applying a coupon is O(1). The table itself takes space proportional to the number of coupons.

    Edge cases and common mistakes

    • Unknown code. Without a default, the lookup yields null and the subtraction doesn't compile. With the default, an unknown code costs the shopper nothing and gives nothing.
    • Letter case. A shopper typing save20 gets no discount, because the keys are matched exactly.
    • A discount bigger than the subtotal. The solution only subtracts, so nothing stops the total from going negative.
    • Printing the discount instead of the total. The output asks for the total after the coupon, not the amount taken off.

    Testing

    Change coupon and run again. With SAVE99 the program prints:

    Total: $100

    With save20, in lowercase, it also prints Total: $100. And with SAVE50 on a subtotal of 30, the program prints:

    Total: $-20

    That last result shows the gap in the rules: a real shop would cap the discount at the subtotal, but this version doesn't.

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