Enum
Enums in Scala 3 provide a way to define a group of named values, known as enumeration constants. Scala 3's enum is a significant enhancement over the older Enumeration class in Scala 2, offering more capabilities and integrating more seamlessly with the type system. Enums are useful for representing a fixed set of constants, such as days of the week, states of a process, or categories of items, with the benefits of type safety and easy pattern matching.
Basic Enum Declaration
To declare an enum in Scala 3, use the enum keyword followed by the name of the enum and a block containing its cases:
enum Color:
case Red, Green, Blue
Here, Color is an enum with three possible values: Red, Green, and Blue.
Using Enums
You can use enums in your Scala code like this:
val myColor: Color = Color.Red
myColor match
case Color.Red => println("Chosen color is Red")
case Color.Green => println("Chosen color is Green")
case Color.Blue => println("Chosen color is Blue")
This code demonstrates defining an enum variable and using pattern matching to perform different actions based on the enum's value.
Parameterized Enums
Enums in Scala 3 can also have parameters, allowing each case to carry additional information:
enum Planet(mass: Double, radius: Double)
case Earth extends Planet(5.972e24, 6.371e6)
case Jupiter extends Planet(1.898e27, 6.9911e7)
case Mars extends Planet(6.39e23, 3.3895e6)
// A method that calculates the surface gravity of a planet
def surfaceGravity: Double = Planet.G * mass / (radius * radius)
}
object Planet:
private final val G = 6.67430e-11 // gravitational constant
In this example, each Planet case has its mass and radius. This makes enums very powerful, as they can encapsulate data and behavior.
Enum Methods and Values
Scala enums can have their methods, as shown with the surfaceGravity method in the Planet example. You can also list all enum values using the .values method:
val planets = Planet.values
planets.foreach(planet =>
println(s"${planet}: Surface gravity = ${planet.surfaceGravity}")
)
This code prints the surface gravity for each planet defined in the Planet enum.
Enumerations with Sealed Trait Pattern (Scala 2 Approach)
Before Scala 3, a common way to simulate enums was using a sealed trait and case objects:
sealed trait Direction
case object North extends Direction
case object East extends Direction
case object South extends Direction
case object West extends Direction
While this pattern is still useful, especially for compatibility with Scala 2 codebases, Scala 3 enums offer a more integrated and straightforward way to define enumeration types.