8. Modelling with types
What time did the Nakamuras sit down? Why did the Haddads cancel? Our bookings can’t say, because a Status is one of six names with nowhere to keep a time or a reason.
A Java developer might add two fields to Booking, seatedAt and cancellationReason, both null most of the time, with a comment saying which statuses fill them in. In Scala each status can carry its own data. The compiler then checks that every seated booking has a time and every cancelled one a reason.
8.1. Cases that carry data
Replace Status in model.scala:
enum Status:
case Requested, Confirmed, Completed, NoShow
case Seated(at: LocalTime)
case Cancelled(reason: String)
The Seated case now has the time the party sat down and Cancelled has a reason, while the other four statuses are still plain names. A case with fields behaves like a small case class: you build one with Status.Cancelled("flu"), two of them with the same reason are equal, and a pattern can take one apart.
Compiling the project now gives errors in five places, though the compiler may not report all five at once. Each is a line that uses Status.Seated or Status.Cancelled with no argument, where it now needs a time or a reason. Three of them are the first three bookings in tonight.scala. Replace those with:
Booking(Party("Haddad", 6), Table(5, 6), LocalTime.of(18, 0),
Status.Cancelled("rang to cancel")),
Booking(Party("Nakamura", 2), Table(2, 2), LocalTime.of(18, 30),
Status.Seated(LocalTime.of(18, 25))),
Booking(Party("Abara", 4), Table(4, 4), LocalTime.of(18, 45),
Status.Seated(LocalTime.of(18, 50))),
In walkIn, in the Booking companion, Status.Seated becomes Status.Seated(now). The fifth is the line inside the for in lastTable. Change it to seat the regulars with walkIn: store.add(Booking.walkIn(Party("Regular", table.seats), table, eight)).
Compile again:
$ scala compile .
[warn] ./desk.scala:3:40
[warn] match may not be exhaustive.
[warn]
[warn] It would fail on pattern case: fullybooked.Status.Seated(_), fullybooked.Status.Cancelled(_)
[warn] def describe(status: Status): String = status match
[warn] ^^^^^^
[warn] ./desk.scala:6:8
[warn] Unreachable case
[warn] case Status.Seated => "at the table"
[warn] ^^^^^^^^^^^^^
[warn] ./desk.scala:8:8
[warn] Unreachable case
[warn] case Status.Cancelled => "cancelled"
[warn] ^^^^^^^^^^^^^^^^
The first warning lists the two cases that describe no longer covers. The other two call its Status.Seated and Status.Cancelled lines unreachable. Written with no arguments, Status.Seated is the companion object that builds Seated values. No status is ever equal to that, so neither that line nor the Status.Cancelled one can ever match. Replace describe in desk.scala:
def describe(status: Status): String = status match
case Status.Requested => "waiting to be confirmed"
case Status.Confirmed => "confirmed"
case Status.Seated(at) => s"at the table since $at"
case Status.Completed => "been and gone"
case Status.Cancelled(reason) => s"cancelled ($reason)"
case Status.NoShow => "never turned up"
The pattern Status.Seated(at) matches any seated status and gives its time the name at.
holdsTable got no warning at all, yet it’s the one with the bug. Its pattern Status.Confirmed | Status.Seated stopped matching seated bookings, because that Status.Seated is the companion too. Its second case is case _ => false, so every party that’s sitting at a table is now reported as not holding it. freeFor would offer their table to someone else. The compiler said nothing: a catch-all silences the missing-case warning, and an alternative inside a | that can never match isn’t reported as unreachable. Replace holdsTable with a version that names every status:
def holdsTable(booking: Booking): Boolean = booking.status match
case Status.Confirmed | Status.Seated(_) => true
case Status.Requested | Status.Completed | Status.NoShow | Status.Cancelled(_) => false
When a seventh status is added, the compiler will warn about this version until someone decides which side the new status belongs on. I don’t use case _ in a match over an enum of my own unless the enum is very large.
Three lines in the tests need a time or a reason as well before they’ll compile. In availability.test.scala, build the Nakamura booking with Booking.walkIn(Party("Nakamura", 2), Table(1, 2), LocalTime.of(18, 30)) and change the cancelled status to Status.Cancelled("flu"). Make the same change to the cancelled booking in deposits.test.scala. If you kept a test of Status.valueOf from chapter 6’s exercises, delete it, because Status no longer has that method. Then run the tests, and frontDesk:
$ scala run . --main-class fullybooked.frontDesk
18:00 table 5: Haddad, party of 6, cancelled (rang to cancel)
18:30 table 2: Nakamura, party of 2, at the table since 18:25
18:45 table 4: Abara, party of 4, at the table since 18:50
19:30 table 5: Okonkwo, party of 5, confirmed
19:30 table 1: Patel, party of 2, waiting to be confirmed
20:00 table 6: Lindqvist, party of 7 (deposit taken), confirmed
20:15 table 3: Moreau, party of 3, confirmed
21:15 table 2: Fitzgerald, party of 2, confirmed
Like a Java enum, a Scala enum normally has values and valueOf. Status lost both when two of its cases gained fields, because there’s no longer a fixed list of values to return.
8.2. What can happen to a booking
A status is where a booking has got to. It gets there through events: the restaurant confirms the booking, and the party arrives, leaves, cancels or never shows up. Create events.scala:
package fullybooked
import java.time.LocalTime
sealed trait Event
case object Confirm extends Event
case class Arrive(at: LocalTime) extends Event
case object Leave extends Event
case class Cancel(reason: String) extends Event
case object FailToArrive extends Event
An enum is shorthand for this: a trait and an implementation for each case. The two events with fields are case classes. The three without are case objects, each of them a single value. sealed means that anything extending Event directly has to be in this file. Java has had sealed interfaces since Java 17, where a permits list can name implementations in other files. The compiler then knows the full list and can warn about a match on an Event that misses a case.
In new Scala 3 code I’d write Event as an enum, which is exercise 2. I’ve written it out in full because enum arrived with Scala 3, so Scala 2 code usually has a sealed trait where Scala 3 would have an enum. A sealed trait is still needed in Scala 3 when one of the cases wants methods of its own, which an enum case can’t have.
Which events are allowed depends on the status, so the method that applies the rules takes both. Add it to events.scala:
def next(status: Status, event: Event): Option[Status] = (status, event) match
case (Status.Requested, Confirm) => Some(Status.Confirmed)
case (Status.Confirmed, Arrive(at)) => Some(Status.Seated(at))
case (Status.Confirmed, FailToArrive) => Some(Status.NoShow)
case (Status.Seated(_), Leave) => Some(Status.Completed)
case (Status.Requested | Status.Confirmed, Cancel(reason)) =>
Some(Status.Cancelled(reason))
case _ => None
The match is on a tuple of the status and the event, with a case for each permitted move. A requested booking can be confirmed, a confirmed one can arrive or fail to, and so on down. In the case for Cancel, the | from chapter 3 sits inside a tuple pattern. Every other combination falls to the final case and gets None. I said I avoid case _, but there are thirty combinations here and “everything else isn’t allowed” is exactly what the rule says.
Give Booking a method that calls next with its own status, inside the class after leaveBy:
def handle(event: Event): Option[Booking] =
next(status, event).map(newStatus => copy(status = newStatus))
Another @main at the end of main.scala puts one booking through an evening:
@main def lifecycle(): Unit =
var booking = Booking(Party("Moreau", 3), Table(3, 4), LocalTime.of(20, 15))
val events = List(Confirm, Arrive(LocalTime.of(20, 10)), Cancel("too noisy"), Leave)
for event <- events do
booking.handle(event) match
case Some(changed) =>
booking = changed
println(s"$event: ${describe(booking.status)}")
case None =>
println(s"$event: not allowed while ${describe(booking.status)}")
$ scala run . --main-class fullybooked.lifecycle
Confirm: confirmed
Arrive(20:10): at the table since 20:10
Cancel(too noisy): not allowed while at the table since 20:10
Leave: been and gone
The Moreaus are confirmed, arrive and then try to cancel, which a seated party can’t do. Their booking is left as it was and the next event carries on from there. The events print as Confirm and Arrive(20:10) because case objects and case classes come with a toString.
Chapter 1 said that a cancelled booking must not be seated. Put that in a test, along with some of the other rules. Create events.test.scala:
package fullybooked
import java.time.LocalTime
class EventTests extends munit.FunSuite:
val eight = LocalTime.of(20, 0)
val requested = Booking(Party("Moreau", 3), Table(3, 4), eight)
test("a booking goes from requested to completed"):
val events = List(Confirm, Arrive(eight), Leave)
val end = events.foldLeft(Option(requested)): (booking, event) =>
booking.flatMap(_.handle(event))
assertEquals(end.map(_.status), Some(Status.Completed))
test("a cancelled booking can't be seated"):
val cancelled = requested.handle(Cancel("flu"))
assertEquals(cancelled.map(_.status), Some(Status.Cancelled("flu")))
assertEquals(cancelled.flatMap(_.handle(Arrive(eight))), None)
test("a party at its table can't cancel"):
val seated = requested.copy(status = Status.Seated(eight))
assertEquals(seated.handle(Cancel("changed our minds")), None)
test("seated parties hold their table"):
assert(holdsTable(requested.copy(status = Status.Seated(eight))))
The first test folds a list of events over a booking. The fold starts from Option(requested), which has the type Option[Booking]. Some(requested) would have the narrower type Some[Booking], and the compiler would then reject a lambda that can return None. The lambda after the colon takes the booking so far and the next event. Because the lambda uses flatMap, the result becomes None at the first event that isn’t allowed and stays None to the end. The last test would have caught the bug in holdsTable.
At the moment next answers None without saying why, so a member of staff who taps “seat” on a cancelled booking can’t be told what’s wrong. Chapter 9 changes next to return the reason.
8.3. How far to take it
The rules in next are checked when the program runs. The compiler could check them if each state had a type of its own. With a method seat that only accepted a ConfirmedBooking, an attempt to seat a cancelled booking wouldn’t compile, and that rule would need no test.
A list of tonight’s bookings would then hold a mixture of those types, so every method that reads the list would have to check which type each one is. The store, the availability code and most of the tests would all grow. I’d accept that for a small piece of code where a mistake would do real damage. For Fully Booked I’d rather have a status with data and one function that holds the rules.
8.4. A type for phone numbers
Party("07700 900141", 5, Some("Okonkwo")) compiles. The name and the number are both strings, so the compiler can’t tell that they’ve been swapped. Nothing stops “ask for Dev” being stored as a phone number either. Create phone.scala:
package fullybooked
opaque type Phone = String
object Phone:
def parse(text: String): Option[Phone] =
val digits = text.filterNot(_.isWhitespace)
if digits.length >= 10 && digits.forall(_.isDigit) then Some(digits) else None
opaque type Phone = String says that a Phone is a String and that only the code in this file is allowed to know it. Everywhere else Phone is a type of its own. A String isn’t accepted where a Phone is wanted, and a Phone has none of the methods of String. Other code has to get its phone numbers from Phone.parse, which drops the spaces and insists on at least ten digits. parse can call filterNot and forall on a String because a String works as a collection of characters. isWhitespace and isDigit are tests on a single character. Because parse checks what it’s given and nothing else can make a Phone, it’s called a smart constructor.
Change the first line of Party to use Phone:
case class Party(name: String, size: Int, phone: Option[Phone] = None):
In tonight.scala, replace the four bookings from Okonkwo to Moreau:
Booking(Party("Okonkwo", 5, Phone.parse("07700 900141")), Table(5, 6),
LocalTime.of(19, 30), Status.Confirmed),
Booking(Party("Patel", 2, Phone.parse("07700 900129")), Table(1, 2),
LocalTime.of(19, 30)),
Booking(Party("Lindqvist", 7, Phone.parse("07700 900152")), Table(6, 8),
LocalTime.of(20, 0), Status.Confirmed),
Booking(Party("Moreau", 3, Phone.parse("07700 900164")), Table(3, 4),
LocalTime.of(20, 15), Status.Confirmed),
The Some has gone because Phone.parse already returns an Option[Phone], the type the field wants. Both lookUp and reconfirm now print the numbers without their spaces, because that’s how parse keeps them. lookUp still compiles, although its getOrElse("none given") gives a String as the default for an Option[Phone]. Chapter 10 explains why that’s allowed. Outside its own file a Phone has only the methods that every value has, such as toString. Chapter 11 adds some.
At run time a Phone is an ordinary String with no wrapper object around it. The other way of doing this is a case class with one field and a private constructor, case class Phone private (digits: String). That form makes an object for every number. Scala 2 has no opaque type, so code written for it wraps the value in a class as well. Such a class sometimes ends in extends AnyVal, which asks the compiler to leave the wrapper out where it can.
Add a test file, phone.test.scala:
package fullybooked
class PhoneTests extends munit.FunSuite:
test("spaces are dropped from a number"):
assertEquals(Phone.parse("07700 900141").map(_.toString), Some("07700900141"))
test("letters are not a phone number"):
assertEquals(Phone.parse("ask for Dev"), None)
test("a number that is too short is rejected"):
assertEquals(Phone.parse("0770 900"), None)
A badly typed number now becomes None, as though the party had given no number at all. That’s acceptable for the list in tonight.scala, which we typed ourselves. A customer who has just entered a number should be told it’s wrong, and in chapter 9 they are.
8.5. Exercises
Solutions are in the book’s downloadable code, under ch08/exercises.
-
Add an event
Reinstate, which returns a cancelled booking toRequested. Test that it works and that a booking in any other status refuses it. -
Rewrite
Eventas an enum. What has to change innext, inlifecycleand in the tests? -
Write an opaque type
PartySizeoverInt, in a file of its own, with a smart constructorPartySize.from(size: Int): Option[PartySize]that accepts sizes from 1 toBooking.largestParty. -
Callers from abroad give numbers like
+44 7700 900141. ChangePhone.parseto accept a leading+and keep it.startsWithanddropwork on aString. -
Delete
Status.NoShowfrom the second case ofholdsTableand compile. Read the warning, then put it back. What would have happened withcase _ => falseon that line? -
Write
summary(event: Event): String, with a line of text for each kind of event. Leave one case out first and see what the compiler says.