TExcelTAD
Home › Scala › Scala Mini Project

Scala Mini Project: Order Pricing Engine

In this project you will build a small order-pricing engine for an online shop, step by step. It takes a customer's order, validates it, applies discount rules, adds tax and prints a receipt. Along the way you will use almost everything from this course: case classes, enums, collections, Option/Either, higher-order functions, extension methods and givens.

Each step is a complete, single-file program, so you can copy any of them and run it with scala run.

Step Goal Main concepts
1 Model the domain case classes, enum, BigDecimal
2 Compute subtotals collection methods, extension methods
3 Validate orders Either, for comprehensions
4 Discount rules functions as values, Option, flatMap
5 Tax and receipt givens, match, string formatting

Step 1: Model the domain

Money is stored as BigDecimal to avoid floating-point surprises. Categories matter later for tax, so they are an enum.

scala · try it yourself
enum Category:
  case Food, Books, Electronics

case class Product(sku: String, name: String, price: BigDecimal, category: Category)
case class Line(product: Product, qty: Int)
case class Order(id: String, customer: String, lines: List[Line], coupon: Option[String])

val catalog: Map[String, Product] = List(
  Product("F-01", "Coffee beans", BigDecimal("12.90"), Category.Food),
  Product("B-07", "Scala book",   BigDecimal("39.00"), Category.Books),
  Product("E-12", "Headphones",   BigDecimal("89.50"), Category.Electronics)
).map(p => p.sku -> p).toMap

@main def run(): Unit =
  val order = Order("A-100", "Mina",
    List(Line(catalog("F-01"), 2), Line(catalog("B-07"), 1)), coupon = Some("WELCOME"))
  println(order.id)
  order.lines.foreach(l => println(s"  ${l.qty} x ${l.product.name} @ ${l.product.price}"))
  println(order.coupon.getOrElse("no coupon"))
A-100
  2 x Coffee beans @ 12.90
  1 x Scala book @ 39.00
WELCOME

Step 2: Compute subtotals

Extension methods keep the case classes small while giving them convenient computed properties.

scala · try it yourself
enum Category:
  case Food, Books, Electronics

case class Product(sku: String, name: String, price: BigDecimal, category: Category)
case class Line(product: Product, qty: Int)
case class Order(id: String, customer: String, lines: List[Line], coupon: Option[String])

extension (l: Line) def total: BigDecimal = l.product.price * l.qty

extension (o: Order)
  def subtotal: BigDecimal = o.lines.map(_.total).sum
  def itemCount: Int = o.lines.map(_.qty).sum
  def byCategory: Map[Category, BigDecimal] =
    o.lines.groupMapReduce(_.product.category)(_.total)(_ + _)

@main def run(): Unit =
  val coffee = Product("F-01", "Coffee beans", BigDecimal("12.90"), Category.Food)
  val book = Product("B-07", "Scala book", BigDecimal("39.00"), Category.Books)
  val order = Order("A-100", "Mina", List(Line(coffee, 2), Line(book, 1)), None)
  println(order.subtotal)
  println(order.itemCount)
  Category.values.foreach(c => println(s"$c: ${order.byCategory.getOrElse(c, BigDecimal(0))}"))
64.80
3
Food: 25.80
Books: 39.00
Electronics: 0

Step 3: Validate orders

A typed error enum plus Either describes everything that can go wrong. Each check is a small function; traverse-style code turns raw SKUs into lines and stops at the first problem.

scala · try it yourself
enum Category:
  case Food, Books, Electronics

case class Product(sku: String, name: String, price: BigDecimal, category: Category)
case class Line(product: Product, qty: Int)

enum OrderError:
  case EmptyOrder
  case UnknownSku(sku: String)
  case BadQuantity(sku: String, qty: Int)

val catalog = Map(
  "F-01" -> Product("F-01", "Coffee beans", BigDecimal("12.90"), Category.Food),
  "B-07" -> Product("B-07", "Scala book", BigDecimal("39.00"), Category.Books)
)

def toLine(sku: String, qty: Int): Either[OrderError, Line] =
  for
    product <- catalog.get(sku).toRight(OrderError.UnknownSku(sku))
    _       <- Either.cond(qty > 0 && qty <= 10, (), OrderError.BadQuantity(sku, qty))
  yield Line(product, qty)

def buildLines(request: List[(String, Int)]): Either[OrderError, List[Line]] =
  if request.isEmpty then Left(OrderError.EmptyOrder)
  else
    request.foldLeft[Either[OrderError, List[Line]]](Right(Nil)) { case (acc, (sku, qty)) =>
      for
        lines <- acc
        line  <- toLine(sku, qty)
      yield lines :+ line
    }

@main def run(): Unit =
  println(buildLines(List("F-01" -> 2, "B-07" -> 1)).map(_.map(l => s"${l.qty}x${l.product.sku}")))
  println(buildLines(List("F-01" -> 2, "X-99" -> 1)))
  println(buildLines(List("B-07" -> 0)))
  println(buildLines(Nil))
Right(List(2xF-01, 1xB-07))
Left(UnknownSku(X-99))
Left(BadQuantity(B-07,0))
Left(EmptyOrder)

Step 4: Discount rules as functions

A discount rule is just a function from an order to an optional discount. New promotions are new functions — no if chains to edit. The engine applies every rule and keeps the best single discount.

scala · try it yourself
case class Line(name: String, price: BigDecimal, qty: Int)
case class Order(lines: List[Line], coupon: Option[String]):
  def subtotal: BigDecimal = lines.map(l => l.price * l.qty).sum

case class Discount(label: String, amount: BigDecimal)
type Rule = Order => Option[Discount]

val welcomeCoupon: Rule = o =>
  o.coupon.filter(_ == "WELCOME").map(_ => Discount("WELCOME coupon", BigDecimal(5)))

def percentOver(threshold: BigDecimal, percent: Int): Rule = o =>
  Option.when(o.subtotal >= threshold)(
    Discount(s"$percent% over $threshold", (o.subtotal * percent / 100).setScale(2)))

val bulkBuy: Rule = o =>
  o.lines.find(_.qty >= 3).map(l => Discount(s"3+ ${l.name}: one free", l.price))

val rules: List[Rule] = List(welcomeCoupon, percentOver(BigDecimal(50), 10), bulkBuy)

def bestDiscount(o: Order): Option[Discount] =
  rules.flatMap(rule => rule(o)).maxByOption(_.amount)

@main def run(): Unit =
  val orders = List(
    Order(List(Line("Coffee", BigDecimal("12.90"), 2)), Some("WELCOME")),
    Order(List(Line("Book", BigDecimal("39.00"), 2)), Some("WELCOME")),
    Order(List(Line("Tea", BigDecimal("4.50"), 4)), None),
    Order(List(Line("Pen", BigDecimal("1.20"), 1)), None)
  )
  for o <- orders do
    val d = bestDiscount(o)
    println(s"subtotal ${o.subtotal} -> ${d.fold("no discount")(d => s"${d.label}: -${d.amount}")}")
subtotal 25.80 -> WELCOME coupon: -5
subtotal 78.00 -> 10% over 50: -7.80
subtotal 18.00 -> 3+ Tea: one free: -4.50
subtotal 1.20 -> no discount

Step 5: Tax and receipt — the complete engine

The final version puts everything together. Tax rates differ per category and are provided as a given, so a different country can plug in its own rates without touching the pricing code.

scala · try it yourself
enum Category:
  case Food, Books, Electronics

case class Product(sku: String, name: String, price: BigDecimal, category: Category)
case class Line(product: Product, qty: Int):
  def total: BigDecimal = product.price * qty
case class Order(id: String, lines: List[Line], coupon: Option[String]):
  def subtotal: BigDecimal = lines.map(_.total).sum

case class Discount(label: String, amount: BigDecimal)
type Rule = Order => Option[Discount]

trait TaxRates:
  def rate(c: Category): BigDecimal

given TaxRates with
  def rate(c: Category) = c match
    case Category.Food        => BigDecimal("0.07")
    case Category.Books       => BigDecimal("0.00")
    case Category.Electronics => BigDecimal("0.19")

val rules: List[Rule] = List(
  o => o.coupon.filter(_ == "WELCOME").map(_ => Discount("WELCOME coupon", BigDecimal(5))),
  o => Option.when(o.subtotal >= 100)(Discount("10% over 100", (o.subtotal / 10).setScale(2)))
)

def tax(o: Order)(using rates: TaxRates): BigDecimal =
  o.lines.map(l => l.total * rates.rate(l.product.category)).sum
    .setScale(2, BigDecimal.RoundingMode.HALF_UP)

def receipt(o: Order)(using TaxRates): List[String] =
  val discount = rules.flatMap(_(o)).maxByOption(_.amount)
  val discountAmount = discount.map(_.amount).getOrElse(BigDecimal(0))
  val taxAmount = tax(o)
  val total = o.subtotal - discountAmount + taxAmount
  def row(label: String, amount: BigDecimal) = f"$label%-28s ${amount.setScale(2)}%9s"
  val itemRows = o.lines.map(l => row(s"${l.qty} x ${l.product.name}", l.total))
  List(s"Receipt ${o.id}", "-" * 38) ++ itemRows ++ List(
    "-" * 38,
    row("Subtotal", o.subtotal)
  ) ++ discount.map(d => row(d.label, -d.amount)).toList ++ List(
    row("Tax", taxAmount),
    row("TOTAL", total)
  )

@main def run(): Unit =
  val coffee = Product("F-01", "Coffee beans", BigDecimal("12.90"), Category.Food)
  val book = Product("B-07", "Scala book", BigDecimal("39.00"), Category.Books)
  val phones = Product("E-12", "Headphones", BigDecimal("89.50"), Category.Electronics)
  val order = Order("A-100", List(Line(coffee, 2), Line(book, 1), Line(phones, 1)), Some("WELCOME"))
  receipt(order).foreach(println)
Receipt A-100
--------------------------------------
2 x Coffee beans                 25.80
1 x Scala book                   39.00
1 x Headphones                   89.50
--------------------------------------
Subtotal                        154.30
10% over 100                    -15.43
Tax                              18.81
TOTAL                           157.68

The 10% discount (15.43) beat the 5.00 coupon, so only the best discount was applied. Tax is 7% of 25.80 (1.806) plus 19% of 89.50 (17.005), rounded to 18.81.

Ideas for extending the project

Extension Concepts to practise
Allow stacking of discounts with a maximum total foldLeft, min
Use an opaque type Money instead of raw BigDecimal opaque types, extension methods
Load the catalog from a CSV string split, Either for parse errors
Price several orders concurrently Future.traverse, Await
Write munit tests for every rule munit, pure functions
A Show[Order] type class for different receipt formats type classes, givens

Tip: Notice that every function in the engine is pure: given the same order it always returns the same result and changes nothing. That is what makes each step easy to test, reuse and reason about.

Test yourself

Why is money stored as BigDecimal in this project?

  1. It is faster than Double
  2. It represents decimal amounts like 12.90 exactly
  3. Scala has no Double
  4. It uses less memory

What is the type of a discount rule in Step 4?

  1. Discount
  2. Order => Option[Discount]
  3. List[Discount]
  4. Either[String, Discount]

Why are tax rates provided as a given TaxRates?

  1. Givens are faster
  2. So another set of rates can be supplied without changing the pricing functions
  3. Because BigDecimal requires it
  4. To make the rates mutable