Data first
Most programs spend their lives moving data around: an order with its lines and a delivery address, a sensor reading with a time and a value, a shape that is a circle or a rectangle or a triangle. Before you write any logic, it pays to describe that data exactly, so the compiler knows what is possible and what is not.
Scala gives you two complementary tools for this. Case classes describe data that has several parts at once: a point has an x and a y. Enums (and their older cousin, sealed traits) describe data that is one of several alternatives: a shape is a circle or a rectangle. Combine the two and you can describe almost any domain precisely. Programmers call such types algebraic data types, because they are built by "multiplying" fields together and "adding" alternatives.
The third tool, pattern matching, is how you work with that data: a match expression asks "which alternative is this, and what is inside it?" and the compiler checks that you have handled every alternative. Together, these three ideas are the heart of everyday Scala, and you will use them in every lesson from here on.
Before them, though, a quick look at ordinary classes and objects, which Scala shares with Java and which case classes are built on.
Classes and objects
Definition— Class
A class is a template for objects. In Scala the constructor parameters are written right after the class name: class Account(val owner: String, opening: BigDecimal). A parameter marked val becomes a public, read-only field; an unmarked one is visible only inside the class. Create an instance with Account("Nomvula", 100); in Scala 3 the keyword new is optional.
Definition— Object
An object is a class with exactly one instance, created the first time it is used. Objects hold constants and functions that do not belong to any particular instance, the role static members play in Java. An object with the same name as a class, in the same file, is its companion object; class and companion can see each other's private members, and the companion is the conventional home for factory methods.
class Account(val owner: String, opening: BigDecimal):
private var balance: BigDecimal = opening
def deposit(amount: BigDecimal): Unit =
require(amount > 0, "a deposit must be positive")
balance += amount
def current: BigDecimal = balance
override def toString: String = s"Account($owner, $balance)"
object Temperature:
val AbsoluteZeroC = -273.15
def toFahrenheit(c: Double): Double = c * 9 / 5 + 32
@main def classes(): Unit =
val acct = Account("Nomvula", 100)
acct.deposit(50)
println(acct.owner)
println(acct.current)
println(acct)
println(Account("Ravi", 5) == Account("Ravi", 5))
println(Temperature.toFahrenheit(37.0))
println(Temperature.AbsoluteZeroC)Nomvula
150
Account(Nomvula, 150)
false
98.6
-273.15Account has hidden, mutable state (private var balance) and methods that guard it: require throws an IllegalArgumentException if its condition is false, which is the idiomatic way to check a method's arguments. current is a method without parentheses; by convention, methods with no side effects are written without (). And toString is overridden, with the override keyword the compiler insists on, so the account prints nicely.
Notice the false. Two separately created Accounts with the same contents are not equal: an ordinary class compares by identity, as in Java. For an object with changing state, such as a bank account, that is exactly right; two accounts that happen to hold the same balance today are still different accounts. For plain data, it is not what you want, and that is what case classes are for.
Case classes: immutable data
Put case in front of class and the compiler writes a lot of useful code for you:
case class Point(x: Double, y: Double):
def distanceTo(other: Point): Double = math.hypot(x - other.x, y - other.y)
case class Student(name: String, year: Int, courses: List[String])
@main def caseClasses(): Unit =
val p = Point(3, 4)
println(p)
println(p.distanceTo(Point(0, 0)))
println(p == Point(3.0, 4.0))
println(Set(Point(1, 2), Point(1, 2), Point(2, 1)).size)
val moved = p.copy(y = 10)
println(moved)
println(p)
val s = Student("Ingrid", 2, List("Algebra", "Physics"))
val next = s.copy(year = s.year + 1, courses = "Chemistry" :: s.courses)
println(next)
val Point(px, py) = p
println(px + py)Point(3.0,4.0)
5.0
true
2
Point(3.0,10.0)
Point(3.0,4.0)
Student(Ingrid,3,List(Chemistry, Algebra, Physics))
7.0A case class gets:
- public, immutable fields for every constructor parameter (no
valneeded); - structural equality and a matching
hashCode: two points with the same coordinates are equal, so the set above has only two elements; - a readable
toString; - a
copymethod that builds a new instance with some fields changed.p.copy(y = 10)leavespuntouched. This is how you "update" immutable data: you don't change the old value, you make a new one that differs where you say; - an extractor, which lets you take an instance apart with a pattern, as in
val Point(px, py) = p, and, far more often, inmatch.
"Chemistry" :: s.courses builds a new list with one more element at the front (lesson 5 explains ::). The old list is shared, not copied, which is why immutable updates are cheaper than they look.
Case classes are the default way to model data in Scala. Use a plain class when an object has identity and changing state, like the account above, or when you need to hide its representation.
Enums and algebraic data types
An enum lists the alternatives a value can be. In its simplest form it is a set of named constants; its cases can also carry data, and then it is a full algebraic data type:
enum Suit:
case Clubs, Diamonds, Hearts, Spades
def isRed: Boolean = this == Hearts || this == Diamonds
enum Shape:
case Circle(radius: Double)
case Rectangle(width: Double, height: Double)
case Triangle(a: Double, b: Double, c: Double)
def area(shape: Shape): Double = shape match
case Shape.Circle(r) => math.Pi * r * r
case Shape.Rectangle(w, h) => w * h
case Shape.Triangle(a, b, c) =>
val s = (a + b + c) / 2
math.sqrt(s * (s - a) * (s - b) * (s - c))
@main def enums(): Unit =
println(Suit.values.toList)
println(Suit.Hearts.ordinal)
println(Suit.valueOf("Spades"))
println(Suit.values.filter(_.isRed).toList)
val shapes = List(Shape.Circle(1), Shape.Rectangle(2, 3), Shape.Triangle(3, 4, 5))
for shape <- shapes do
println(f"${shape.toString}%-22s area ${area(shape)}%.2f")List(Clubs, Diamonds, Hearts, Spades)
2
Spades
List(Diamonds, Hearts)
Circle(1.0) area 3.14
Rectangle(2.0,3.0) area 6.00
Triangle(3.0,4.0,5.0) area 6.00- A simple enum like
Suitgetsvalues(all cases, in order),ordinal(a case's position, from 0) andvalueOf(look a case up by name). Enums can have methods, likeisRed. - Each case of
Shapeis effectively a case class, so it has fields, equality,toStringand an extractor. AShapeis exactly one of the three; there is no fourth possibility. areahandles each case. The triangle uses Heron's formula from the three side lengths.
Before Scala 3, the same type was written as a sealed trait with case classes extending it, and you will see this in a lot of existing code (and still today, when the alternatives need to be spread over a richer hierarchy):
sealed trait Shape
case class Circle(radius: Double) extends Shape
case class Rectangle(width: Double, height: Double) extends Shapesealed means every direct subtype must be declared in the same file. That is what lets the compiler know the complete list of alternatives.
The exhaustiveness check
Because the compiler knows every case of an enum or sealed trait, it checks that each match handles them all. Forget one:
def symbol(s: Suit): String = s match
case Suit.Clubs => "♣"
case Suit.Diamonds => "♦"
case Suit.Hearts => "♥"and the compiler warns, naming the missing case:
-- [E029] Pattern Match Exhaustivity Warning: main.scala:4:30
4 |def symbol(s: Suit): String = s match
| ^
| match may not be exhaustive.
|
| It would fail on pattern case: SpadesIf the program ran anyway and reached that match with Spades, it would throw a MatchError. This check is one of Scala's most valuable features in real projects: when someone adds a fifth case to an enum next year, the compiler lists every match in the code base that needs updating. Many teams compile with warnings treated as errors (the -Werror option) precisely so that such warnings can never be ignored.
Pattern matching in depth
A match expression tries each case in order and evaluates the first one whose pattern fits. Patterns can test types, take apart structures, bind names and nest inside each other:
case class Address(city: String, country: String)
case class Person(name: String, age: Int, address: Option[Address])
def describe(x: Any): String = x match
case 0 => "zero"
case n: Int if n < 0 => s"a negative Int, $n"
case n: Int => s"a positive Int, $n"
case s: String if s.isEmpty => "an empty string"
case s: String => s"a string of length ${s.length}"
case (a, b) => s"a pair of $a and $b"
case Nil => "an empty list"
case List(only) => s"a list holding just $only"
case first :: rest => s"a list starting with $first, then ${rest.size} more"
case _ => "something else"
def greeting(p: Person): String = p match
case Person(name, age, _) if age < 13 => s"Hi, $name!"
case Person(name, _, Some(Address(_, "Brazil"))) => s"Olá, $name!"
case Person(name, _, Some(home @ Address(city, _))) => s"Hello, $name from $city ($home)"
case Person(name, _, None) => s"Hello, $name, wherever you are"
@main def patterns(): Unit =
for x <- List(0, -5, 42, "", "Scala", ("km", 3), Nil, List('a'), List(1, 2, 3), 2.5) do
println(describe(x))
println(greeting(Person("Tavita", 9, None)))
println(greeting(Person("Joana", 30, Some(Address("Recife", "Brazil")))))
println(greeting(Person("Arjun", 41, Some(Address("Pune", "India")))))
println(greeting(Person("Elif", 25, None)))zero
a negative Int, -5
a positive Int, 42
an empty string
a string of length 5
a pair of km and 3
an empty list
a list holding just a
a list starting with 1, then 2 more
something else
Hi, Tavita!
Olá, Joana!
Hello, Arjun from Pune (Address(Pune,India))
Hello, Elif, wherever you areThe kinds of pattern used here:
| Pattern | Matches | Example |
|---|---|---|
| Literal | a value equal to the literal | 0, "Brazil", Nil |
| Variable | anything, and binds it to the name | name, rest |
| Wildcard | anything, binding nothing | _ |
| Typed | a value of that type, bound with that type | n: Int, s: String |
| Constructor | a case class or enum case, with patterns for its fields | Address(_, "Brazil") |
| Tuple | a tuple of that size | (a, b) |
| List | a list of a given length, or head and tail | List(only), first :: rest |
| Binder | the pattern on the right, and binds the whole value | home @ Address(city, _) |
| Alternative | either pattern | "Saturday" | "Sunday" |
A guard, if condition after a pattern, adds an extra test. Order matters: the general n: Int case comes after the more specific ones, or they would never be reached. And Option[Address], which you will meet properly in lesson 7, is itself an algebraic data type with two cases, Some(value) and None, so it is matched just like your own enums.
describe takes Any, which is only for demonstration. In real code, matching on Any throws away the exhaustiveness check, because the compiler cannot list every possible type. Keep your matches on enums and sealed types, and the compiler will keep you honest.
Modelling a domain: make illegal states unrepresentable
Experienced Scala programmers spend real effort on their data types, because a well-chosen type removes whole categories of bugs before any logic is written. The slogan is make illegal states unrepresentable: design types so that values which make no sense in your domain cannot even be constructed.
Consider an online order's payment. A first attempt often looks like this: paid: Boolean, refunded: Boolean, reference: String, refundReason: String. That allows nonsense: refunded but never paid, a refund reason on an unrefunded order, an empty reference on a paid one. Every function that touches an order must defend against these impossible combinations, and sooner or later one forgets. An enum states the truth directly: a payment is pending, or paid with a reference, or refunded with a reference and a reason. Nothing else can exist.
The second technique is the smart constructor: make the case class's constructor private and offer a function in the companion object that validates its input and returns an Option (or, as lesson 7 shows, an Either with an error message). Then every Email value in the program has passed the check, and no other function has to repeat it.
case class Email private (value: String)
object Email:
def from(text: String): Option[Email] =
val t = text.trim.toLowerCase
val parts = t.split('@')
if parts.length == 2 && parts.forall(_.nonEmpty) && parts(1).contains('.') then Some(Email(t))
else None
enum Payment:
case Pending
case Paid(reference: String)
case Refunded(reference: String, reason: String)
case class Order(id: Int, customer: Email, payment: Payment)
def summary(order: Order): String = order.payment match
case Payment.Pending => s"Order ${order.id}: waiting for payment"
case Payment.Paid(ref) => s"Order ${order.id}: paid ($ref)"
case Payment.Refunded(ref, reason) => s"Order ${order.id}: refunded $ref because $reason"
@main def domain(): Unit =
println(Email.from(" Amina@Example.org "))
println(Email.from("not-an-address"))
for email <- Email.from("li.wei@example.cn") do
val orders = List(
Order(1, email, Payment.Pending),
Order(2, email, Payment.Paid("TX-881")),
Order(3, email, Payment.Refunded("TX-412", "it arrived damaged"))
)
orders.map(summary).foreach(println)Some(Email(amina@example.org))
None
Order 1: waiting for payment
Order 2: paid (TX-881)
Order 3: refunded TX-412 because it arrived damagedBecause the constructor is private, writing Email("x") anywhere outside the class and its companion is a compile error (object Email does not take parameters); the generated copy method becomes private too, so nobody can sneak an unchecked value in through it. The address check here is deliberately simple; real e-mail validation is notoriously subtle, and production code usually checks the basic shape and then sends a confirmation message. The for email <- Email.from(...) do line runs its body only if the address was valid, a first glimpse of treating Option like a collection with zero or one elements.
Common misconceptions
Misconception
"copy changes the object." It returns a new object; the original is unchanged, as the second println(p) above shows. If you call p.copy(y = 10) and ignore the result, nothing happens.
Misconception
"A lowercase name in a pattern compares against the variable with that name." In a pattern, a name starting with a lowercase letter is a new variable that matches anything. To compare against an existing value limit, write it in backticks, `limit`, or use a guard, case n if n == limit. Names starting with an uppercase letter (like Nil or an enum case) are treated as constants.
Misconception
"The exhaustiveness check is only a warning, so it doesn't matter." It is the compiler telling you about a MatchError waiting to happen at run time. Treat it as an error; most professional builds do.
Misconception
"Case classes can't have methods or validation." They can have any methods, like distanceTo above, and a companion object with smart constructors that validate input. What they should not have is hidden mutable state, because their equality and hash code are based on their fields.
Exercises
1. Case classes, enums and pattern matching
Warm-upComputationalWhat does this program print? Write the three lines separated by single spaces.
case class Book(title: String, year: Int)
@main def ex(): Unit =
val a = Book("Ficciones", 1944)
val b = a.copy(year = 1956)
println(a == Book("Ficciones", 1944))
println(b.year - a.year)
println(a)
2. Case classes, enums and pattern matching
Warm-upComputationalWhat does this print? Write the two values separated by a space.
class A(val n: Int)
case class B(n: Int)
@main def ex(): Unit =
println(A(1) == A(1))
println(B(1) == B(1))
3. Case classes, enums and pattern matching
CoreComputationalWhat does this program print? Write the three lines separated by single spaces.
def classify(xs: List[Int]): String = xs match
case Nil => "empty"
case x :: Nil => s"one: $x"
case x :: y :: _ if x > y => "starts by falling"
case _ :: rest => s"then ${rest.length} more"
@main def ex(): Unit =
println(classify(List(5, 3, 8)))
println(classify(List(1, 3, 8)))
println(classify(List(9)))
4. Case classes, enums and pattern matching
CoreComputationalGiven
enum Day:
case Mon, Tue, Wed, Thu, Fri, Sat, Sun
what is Day.valueOf("Fri").ordinal?
5. Case classes, enums and pattern matching
CoreHumanWhat does this print?
val limit = 10
val r = 3 match
case limit => s"matched $limit"
println(r)
6. Case classes, enums and pattern matching
CoreHumanenum Light: case Red, Amber, Green. Which match makes the compiler warn that it may not be exhaustive?
7. Case classes, enums and pattern matching
StretchHumanWhich of these does the compiler generate for case class Point(x: Double, y: Double)? Choose all that apply.
Further reading and resources
- Scala 3 Book: Domain Modeling ToolsClasses, objects, companion objects, traits, enums and case classes.
- Enumerations (Scala 3 Reference)
- Pattern matching (Scala 3 Reference)