Scala Enums
An enum defines a type with a fixed set of named values. Scala 3's enum keyword covers everything from simple lists of constants to full algebraic data types (ADTs) whose cases carry data. Before Scala 3 the same ideas required sealed traits and case objects; enum makes them short and readable.
A simple enumeration
enum Weekday:
case Mon, Tue, Wed, Thu, Fri, Sat, Sun
@main def run(): Unit =
val today = Weekday.Wed
println(today)
println(today.ordinal)
println(Weekday.values.mkString(", "))
println(Weekday.valueOf("Fri"))
println(Weekday.fromOrdinal(6))Wed
2
Mon, Tue, Wed, Thu, Fri, Sat, Sun
Fri
Sun
| Member | Meaning |
|---|---|
Weekday.Mon |
one of the cases |
.ordinal |
its zero-based position |
Weekday.values |
an Array of all cases in order |
Weekday.valueOf("Mon") |
look a case up by name (throws if unknown) |
Weekday.fromOrdinal(0) |
look a case up by position |
Matching on enums
Matches over an enum are checked for exhaustiveness: forget a case and the compiler warns you.
enum Weekday:
case Mon, Tue, Wed, Thu, Fri, Sat, Sun
def kind(d: Weekday): String = d match
case Weekday.Sat | Weekday.Sun => "weekend"
case _ => "workday"
@main def run(): Unit =
import Weekday.*
for d <- List(Mon, Fri, Sun) do println(s"$d is a ${kind(d)}")Mon is a workday
Fri is a workday
Sun is a weekend
import Weekday.* brings the cases into scope so you can write Mon instead of Weekday.Mon.
Enums with parameters and methods
Enum cases can share constructor parameters, and the enum body can define methods.
enum Planet(val mass: Double, val radius: Double):
case Mercury extends Planet(3.303e23, 2.4397e6)
case Earth extends Planet(5.976e24, 6.37814e6)
case Jupiter extends Planet(1.9e27, 7.1492e7)
private val G = 6.673e-11
def surfaceGravity: Double = G * mass / (radius * radius)
def weight(massKg: Double): Double = massKg * surfaceGravity
@main def run(): Unit =
for p <- Planet.values do
println(f"${p.toString}%-8s ${p.weight(70)}%7.1f N")Mercury 259.2 N
Earth 686.2 N
Jupiter 1736.4 N
Enums as algebraic data types
Cases can also have their own parameters. Then the enum describes alternatives that carry different data — an ADT. Each case behaves like a case class.
enum Shape:
case Circle(radius: Double)
case Rect(width: Double, height: Double)
case Triangle(base: Double, height: Double)
def area(s: Shape): Double = s match
case Shape.Circle(r) => math.Pi * r * r
case Shape.Rect(w, h) => w * h
case Shape.Triangle(b, h) => b * h / 2
@main def run(): Unit =
val shapes = List(Shape.Circle(1), Shape.Rect(2, 3), Shape.Triangle(4, 5))
shapes.foreach(s => println(f"$s%-22s area ${area(s)}%.2f"))
println(Shape.Rect(2, 3) == Shape.Rect(2, 3))Circle(1.0) area 3.14
Rect(2.0,3.0) area 6.00
Triangle(4.0,5.0) area 10.00
true
Generic ADTs
Enums can have type parameters. This is how you could define your own version of Option:
enum Maybe[+A]:
case Just(value: A)
case Empty
def getOrElse[B >: A](default: B): B = this match
case Just(v) => v
case Empty => default
@main def run(): Unit =
val a: Maybe[Int] = Maybe.Just(5)
val b: Maybe[Int] = Maybe.Empty
println(a.getOrElse(0))
println(b.getOrElse(0))
println(a)5
0
Just(5)
Enum or sealed trait?
| Situation | Choose |
|---|---|
| fixed list of constants | enum |
| alternatives with data, all defined together | enum (ADT) |
| subtypes need to extend other classes or traits too | sealed trait + case classes |
| cases spread across a larger hierarchy | sealed trait |
Tip: Enum cases compile to ordinary objects and classes, so they work in sets, as map keys and in pattern matches — no special handling required.
Test yourself
What does Weekday.Wed.ordinal return when the cases are Mon, Tue, Wed, ...?
- 1
- 2
- 3
- "Wed"
Which line defines an enum case that carries its own data?
case Red, Greencase Circle(radius: Double)val Circle = 1object Circle
What does Weekday.values return?
- A
Setin random order - An
Arrayof all cases in declaration order - The number of cases
- A
Mapfrom names to cases