Let's look at the code for the preceding example, one step at a time. First of all, we have defined a Money class that represents the amount the user requests. The definition looks like the following:
case class Money(amount: Int)
Now, let's have a look at the Dispenser trait. It is the one that the concrete dispensers extend, as shown here:
trait Dispenser { val amount: Int val next: Option[Dispenser] def dispense(money: Money): Unit = { if (money.amount >= amount) { val notes = money.amount / amount val left = money.amount % amount System.out.println(s"Dispensing $notes note/s of $amount.") if (left > 0) next.map(_.dispense(Money(left))) } else { next.foreach(_.dispense(money)) } }}
As we mentioned in the preceding section, ...