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
- Look up the discount. Create
val discountfromcoupons.getOrElse(coupon, 0). The result is anInteither way: the stored discount, or 0. - Compute
totalas the subtotal minus the discount. - Build
resultas"Total: $"followed by the total. The+converts theIntto text when it is added to a string. - Print
resultwithprintln.
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 defaultMapis 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, butcoupons("FREE")throws ajava.util.NoSuchElementExceptionwith the messagekey not found: FREE.coupons.get("FREE")returns anOption:Nonefor a missing key andSome(10)for"SAVE10".getOrElseunwraps 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
couponfinds 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 usesgetOrElse. - Case matters. The key is the exact text, so
"save20"is not"SAVE20". With the lowercase code,getOrElsereturns 0 and the line isTotal: $100. Converting the code withtoUpperCasebefore 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
SAVE50the printed line isTotal: $-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:
| Subtotal | Coupon | Output |
|---|---|---|
| 100 | SAVE20 | Total: $80 |
| 100 | save20 | Total: $100 |
| 100 | FREE | Total: $100 |
| 30 | SAVE50 | Total: $-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.
