3. Case classes, enums and traits

In chapter 2 a quote was held in a tuple, with a note that values which travel around a program together belong in a case class. A booking is that sort of value. It has a party, a table and a time, and later in the chapter it gets a status too. We’ll give each of those a type and write the code that stores and displays bookings, ending up with a small project of several files.

3.1. A booking as data

The fully-booked directory is about to become one program, with all of its files compiled together, and the scripts from chapters 1 and 2 would get in the way: tables.scala has its own Table, and each script has an @main that has nothing to do with the new code. Delete hello.scala, tables.scala and quote.scala, along with anything else you saved while trying things out, or move them to another directory if you’d like to keep them.

Then create a new file called model.scala:

//> using scala 3.9.0
//> using jvm 25

import java.time.LocalTime

case class Table(number: Int, seats: Int)

case class Party(name: String, size: Int)

case class Booking(party: Party, table: Table, time: LocalTime)

Table is the case class from chapter 1. The other two are new, with a Booking holding a Party, a Table and a LocalTime. Load the file into the REPL with scala repl model.scala and make a booking. Because the REPL doesn’t see the file’s own imports, the session starts by importing LocalTime again. LocalTime.of(19, 30) is half past seven in the evening.

scala> import java.time.LocalTime

scala> val booking = Booking(Party("Okonkwo", 5), Table(5, 6), LocalTime.of(19, 30))
val booking: Booking = Booking(
  party = Party(name = "Okonkwo", size = 5),
  table = Table(number = 5, seats = 6),
  time = 19:30
)

scala> booking.party.name
val res0: String = "Okonkwo"

scala> booking == Booking(Party("Okonkwo", 5), Table(5, 6), LocalTime.of(19, 30))
val res1: Boolean = true

scala> val later = booking.copy(time = LocalTime.of(20, 0))
val later: Booking = Booking(
  party = Party(name = "Okonkwo", size = 5),
  table = Table(number = 5, seats = 6),
  time = 20:00
)

scala> booking.time
val res2: LocalTime = 19:30

scala> booking.toString
val res3: String = "Booking(Party(Okonkwo,5),Table(5,6),19:30)"

Laying a case class out with its field names is the REPL’s own way of displaying one. The toString that the compiler generated, which is what println uses, is the more compact text on the last line. The compiler generated equals as well, so two bookings built separately from the same values are ==.

Because the fields of a case class are all vals, a booking can’t be altered once it exists. If the Okonkwos ring to say they’ll be half an hour late, we make a new booking from the old one with copy, naming only the field that differs, and the original still says 19:30. Java’s records have no equivalent, even in Java 25: to change one component of a record, you call the constructor again and pass every component. Making a changed copy and leaving the original alone is the functional-style habit I described in chapter 1.

3.2. Methods on a case class

Chapter 2’s rules were top-level methods that took a party size. A case class can have methods of its own. That lets the rules move onto Party and gives Booking a way to work out when its table has to be given back. Replace Party and Booking with these versions:

case class Party(name: String, size: Int):
  def stayMinutes: Int =
    if size <= 4 then 90 else 120

  def deposit: BigDecimal =
    if size >= 6 then BigDecimal("10.00") * size else BigDecimal(0)

case class Booking(party: Party, table: Table, time: LocalTime):
  def leaveBy: LocalTime = time.plusMinutes(party.stayMinutes)

The colon at the end of case class Party(name: String, size: Int): opens the body of the class, much as = opens the body of a method. Inside it, size is the party’s own field. Since none of the three methods takes arguments and each just returns a value, the convention from chapter 1 says to declare them without parentheses. Calling one looks the same as reading a field. The REPL only reads model.scala when it starts. Quit it and start it again after every change to the file:

scala> import java.time.LocalTime

scala> val booking = Booking(Party("Okonkwo", 5), Table(5, 6), LocalTime.of(19, 30))
val booking: Booking = Booking(
  party = Party(name = "Okonkwo", size = 5),
  table = Table(number = 5, seats = 6),
  time = 19:30
)

scala> booking.leaveBy
val res0: LocalTime = 21:30

scala> booking.party.deposit
val res1: BigDecimal = 0

scala> Party("Lindqvist", 7).deposit
val res2: BigDecimal = 70.00

3.3. Statuses and enums

A booking moves through stages: somebody requests it, the restaurant confirms it, the party turns up and is seated, and at the end of the evening it’s complete. It can also be cancelled, or the party can fail to show. A fixed set of named values like that is an enum. Add an enum above Booking, and replace Booking with a version that has a status:

enum Status:
  case Requested, Confirmed, Seated, Completed, Cancelled, NoShow

case class Booking(
    party: Party,
    table: Table,
    time: LocalTime,
    status: Status = Status.Requested
):
  def leaveBy: LocalTime = time.plusMinutes(party.stayMinutes)

Each value of the enum is introduced by case. One case can introduce several values. The fourth field of Booking has a default value. The three-argument bookings we’ve written so far still compile, and they start out as Requested. With more than two or three parameters, one to a line is easier to read, so that’s how I’ve laid them out.

scala> import java.time.LocalTime

scala> Status.values
val res0: Array[Status] = Array(Requested, Confirmed, Seated, Completed, Cancelled, NoShow)

scala> Status.valueOf("Seated")
val res1: Status = Seated

scala> val booking = Booking(Party("Patel", 2), Table(1, 2), LocalTime.of(19, 30))
val booking: Booking = Booking(
  party = Party(name = "Patel", size = 2),
  table = Table(number = 1, seats = 2),
  time = 19:30,
  status = Requested
)

scala> booking.copy(status = Status.Confirmed)
val res2: Booking = Booking(
  party = Party(name = "Patel", size = 2),
  table = Table(number = 1, seats = 2),
  time = 19:30,
  status = Confirmed
)

values and valueOf behave as they do on a Java enum. The Array that values returns is a Java array. Scala’s enums go further than Java’s, because each case can have fields that the other cases don’t. Chapter 8 uses that.

3.4. Choosing with match

The staff need to see a status in words. Add this to the end of model.scala:

def describe(status: Status): String = status match
  case Status.Requested => "waiting to be confirmed"
  case Status.Confirmed => "confirmed"
  case Status.Seated    => "at the table"
  case Status.Completed => "been and gone"
  case Status.Cancelled => "cancelled"
  case Status.NoShow    => "never turned up"

A match looks like a Java switch. On an enum it behaves like a Java switch expression written with arrows, in that the first case that fits is chosen and there’s no falling through to the next one. A match is an expression, as if is, so describe can return it directly.

Knowing every value of Status, the compiler can tell when a match has left one out. Delete the NoShow line and compile:

$ scala compile model.scala
[warn] ./model.scala:26:40
[warn] match may not be exhaustive.
[warn]
[warn] It would fail on pattern case: NoShow
[warn] def describe(status: Status): String = status match
[warn]                                        ^^^^^^

It’s only a warning, so the file still compiles, although calling describe with NoShow would throw a MatchError at run time. I tend to make all of my warnings hard errors, which we set up in chapter 18. Put the line back.

The check is most useful when the code changes. Add a seventh status next year and the compiler will point out each match like this one that doesn’t handle it yet.

Several values can share a case. Add this method as well:

def holdsTable(booking: Booking): Boolean = booking.status match
  case Status.Confirmed | Status.Seated => true
  case _                                => false

| between patterns means “or”. _ is a pattern that matches anything. On the last line it works as a catch-all, like Java’s default. Because it covers every value, a catch-all also silences the missing-case warning for that match. Save it for when “everything else” is what you mean.

Patterns can also take a case class apart. Add this third method:

def label(booking: Booking): String = booking match
  case Booking(Party(name, size), Table(number, _), time, Status.Confirmed) if size >= 6 =>
    s"$time table $number: $name, party of $size (deposit taken)"
  case Booking(Party(name, size), Table(number, _), time, _) =>
    s"$time table $number: $name, party of $size"

The first pattern, Booking(Party(name, size), Table(number, _), time, Status.Confirmed), matches only a confirmed booking. In the same step it gives names to the parts we want to use: name, size, number and time. The _ inside Table(number, _) skips the seat count. The if that follows is a guard, a further condition the case has to pass. Because cases are tried from the top, the more specific one has to come first.

scala> import java.time.LocalTime

scala> describe(Status.NoShow)
val res0: String = "never turned up"

scala> val patel = Booking(Party("Patel", 2), Table(1, 2), LocalTime.of(19, 30))
val patel: Booking = Booking(
  party = Party(name = "Patel", size = 2),
  table = Table(number = 1, seats = 2),
  time = 19:30,
  status = Requested
)

scala> holdsTable(patel)
val res1: Boolean = false

scala> label(patel)
val res2: String = "19:30 table 1: Patel, party of 2"

scala> label(Booking(Party("Lindqvist", 7), Table(6, 8), LocalTime.of(20, 0), Status.Confirmed))
val res3: String = "20:00 table 6: Lindqvist, party of 7 (deposit taken)"

Java can do a fair amount of this now. Its switch has had patterns for records since Java 21, and a switch expression over an enum has always had to cover every constant. Scala has had match since its early versions, and you’ll probably meet it far more often than you meet switch in Java.

3.5. Where statics went

Scala has no static keyword. A value or method that doesn’t belong to any one instance goes in an object, which defines a class and its single instance in one go. When an object shares its name with a class in the same file, it’s called that class’s companion. It’s the usual home for what Java would make static members of the class. Add one for Booking, again at the end of the file:

object Booking:
  val largestParty = 8

  def walkIn(party: Party, table: Table, now: LocalTime): Booking =
    Booking(party, table, now, Status.Seated)
scala> import java.time.LocalTime

scala> Booking.largestParty
val res0: Int = 8

scala> Booking.walkIn(Party("Moreau", 3), Table(3, 4), LocalTime.of(20, 15))
val res1: Booking = Booking(
  party = Party(name = "Moreau", size = 3),
  table = Table(number = 3, seats = 4),
  time = 20:15,
  status = Seated
)

Booking.walkIn is called like a static factory method. A real Java static such as LocalTime.of looks the same from Scala. The compiler gives every case class a companion whether you write one or not. It contains a method that builds instances, which is what runs when you write Table(5, 6) with no new.

describe and label are top-level methods that could have gone in a companion. I put a method in a companion when it’s about that one type and leave general helpers at the top level.

3.6. Classes and traits

A case class suits data that doesn’t change. The collection of bookings for an evening changes as bookings arrive. For that we want an ordinary class, which I’ll put behind a trait. Add both to model.scala:

trait BookingStore:
  def add(booking: Booking): Unit
  def all: List[Booking]

  def at(time: LocalTime): List[Booking] =
    all.filter(booking => booking.time == time)

class InMemoryBookingStore extends BookingStore:
  private var bookings: List[Booking] = List()

  def add(booking: Booking): Unit =
    bookings = bookings.appended(booking)

  def all: List[Booking] = bookings

A trait is Scala’s version of an interface. BookingStore declares two methods with no body and gives a third, at, a body written in terms of all, as a Java interface can with a default method. InMemoryBookingStore is a plain class that extends the trait and supplies the missing two. A class can extend several traits, separated by commas.

The class keeps its bookings in a private var, the first mutable state in Fully Booked. Only add can change it, by building a new list with appended and storing that in the var. Since an empty List() gives the compiler no element type to infer, the type of bookings is written out.

A plain class doesn’t get the generated methods a case class has. It has no toString, equals or copy of its own, and two stores are equal only when they’re the same object. That suits something with identity and changing state. A class can take parameters as a case class does, class InMemoryBookingStore(limit: Int) for instance, but they’re private to the class unless you mark them val. Scala 3 lets you create an instance of any class without new, as in InMemoryBookingStore().

The trait is there because a second implementation is coming. When the bookings move into a database in chapter 20, code written against BookingStore won’t need to change.

3.7. One project, several files

With data types, display code and storage all in model.scala, it’s time to split the file up.

Create a file called project.scala for the directives, so that they’re stated once for the whole directory:

//> using scala 3.9.0
//> using jvm 25

model.scala keeps the case classes, the enum and the Booking companion. describe, holdsTable and label move to desk.scala, and the trait and its class to store.scala. Take the directives out of model.scala. Each of those three files then starts with a package declaration, followed by the LocalTime import in model.scala and store.scala, which use it:

package fullybooked

import java.time.LocalTime

Packages work as they do in Java, with the exception that the directory structure doesn’t have to match the package name. All the files can sit side by side. Code in one file can use anything from the others in the same package without an import, including top-level methods like label.

A fifth file, main.scala, belongs to the same package and puts the pieces to work:

package fullybooked

import java.time.LocalTime

@main def frontDesk(): Unit =
  val store = InMemoryBookingStore()
  store.add(Booking(Party("Okonkwo", 5), Table(5, 6), LocalTime.of(19, 30), Status.Confirmed))
  store.add(Booking(Party("Patel", 2), Table(1, 2), LocalTime.of(19, 30)))
  store.add(Booking(Party("Lindqvist", 7), Table(6, 8), LocalTime.of(20, 0), Status.Confirmed))
  store.add(Booking.walkIn(Party("Moreau", 3), Table(3, 4), LocalTime.of(20, 15)))

  for booking <- store.all do
    println(s"${label(booking)}, ${describe(booking.status)}")

Run the whole directory by giving the scala command a . in place of a file name:

$ scala run .
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, at the table

The for from chapter 2 walks through a list the same way it walked through a range. store.all is a List[Booking]. Chapter 4 is about what you can do with one.

3.8. Exercises

Solutions are in the book’s downloadable code, under ch03/exercises.

  1. Give Table a method fits(party: Party): Boolean. Try it in the REPL: scala repl . loads the whole project, and import fullybooked.* brings its contents into scope.

  2. Add a Waitlisted case to Status and compile the project with scala compile .. Which match does the compiler warn you about, and why does it say nothing about holdsTable?

  3. Write canSeat(booking: Booking): Boolean. Only a confirmed booking can be shown to its table.

  4. Give Table a companion object holding the restaurant’s six tables as Table.all, then use fits to print the tables that would take a party of 7.

  5. Add a method count: Int to BookingStore, with a body, without touching InMemoryBookingStore. Call it from main.scala.