Enums

An enum names a fixed set of alternatives, and the compiler makes each one a value. It replaces the constants of a Java class and the sealed trait with case objects in one declaration: the cases may be plain singletons, they may carry fields, and the enum may declare methods that all of them share.

A set of constants with a method

Day lists the seven days. The method weekend matches on this, and values gives the cases in declaration order:

days.scala

enum Day: case Mon, Tue, Wed, Thu, Fri, Sat, Sun def weekend: Boolean = this match case Sat | Sun => true case _ => false @main def days(): Unit = println(Day.Mon) println(Day.Mon.ordinal) println(Day.values.length) println(Day.values.filter(_.weekend).mkString(", ")) println(Day.valueOf("Fri")) println(Day.Mon.weekend)

scala-cli run --server=false days.scala

Mon
0
7
Sat, Sun
Fri
false

Day.Mon prints its own name, ordinal is its position from zero, and valueOf turns a name back into a case, which is the one lookup an enum gives away for free. A match over an enum is checked like a match over a sealed trait: leaving a case out is a warning.

A case that carries fields

A case with parameters makes the enum a small hierarchy, and each case is a class of its own. Shape is a circle or a rectangle, and area matches on the case to reach the fields:

shapes.scala

enum Shape: case Circle(radius: Double) case Rectangle(width: Double, height: Double) def area: Double = this match case Circle(r) => math.Pi * r * r case Rectangle(w, h) => w * h @main def shapes(): Unit = val shapes = List(Shape.Circle(1.0), Shape.Rectangle(2.0, 3.0)) shapes.foreach(shape => println(f"${shape.area}%.4f")) println(Shape.Circle(1.0) == Shape.Circle(1.0))

scala-cli run --server=false shapes.scala

3.1416
6.0000
true

A case with fields is a case class in every way that matters: two circles of the same radius are equal, and the pattern Circle(r) binds r. An enum of this shape has no values method, because the values are not a fixed list: Circle(1.0) is one of infinitely many.

Parameters on the enum itself

The parameters of the enum are shared by every case, which is the place for a code or a label. Status gives each case a number, and successful reads it:

status.scala

enum Status(val code: Int): case Ok extends Status(200) case NotFound extends Status(404) case ServerError extends Status(500) def successful: Boolean = code / 100 == 2 @main def statuses(): Unit = Status.values.foreach(status => println(s"${status.code} ${status.successful}")) println(Status.NotFound.toString) println(Status.NotFound.ordinal)

scala-cli run --server=false status.scala

200 true
404 false
500 false
NotFound
1

values works here because every case is a singleton with no fields of its own: the parameter belongs to the enum, and each case passes its own value to it. That is the shape to reach for when the alternatives differ in name and in a few data fields rather than in structure.

Related

Article author: Arthur Isaev