home search about rss feed twitter ko-fi

Enums, Part 1 (Scala 3 Video)

Scala 3 Enums (Enumerations): The Basics

An enum, or enumeration, is a finite set of named values, where the word “set” implies that the values are unique. Examples are:

  • Days in a week (the names Sunday, Monday ... Saturday)
  • Suits and ranks in a deck of cards
  • Pizza toppings, crust sizes, and crust types
  • Simple directions, such as north, south, east, and west

In Scala 3:

  • Enums can be parameterized
  • Enums can have members (fields and methods)

Examples

In an example like this for modeling a deck of cards:

enum Suit:
    case Clubs, Diamonds, Hearts, Spades

we say:

  • Suit is a new type that you have created (just like String and Int are built-in types)
  • Values of that type are Clubs, Diamonds, Hearts, and Spades

Other simple examples:

enum Directions:
    case North, South, East, West

enum Bool:
    case True, False

enum CrustSize:
    case Small, Medium, Large

enum CrustType:
   case Thin, Thick, Regular

enum Topping:
    case Cheese, Mushrooms, GreenPeppers, Olives

Given those pizza-related enums, here’s a small but complete example:

// import the enum values
import CrustSize.*
import CrustType.*
import Topping.*

// use them in a class
case class Pizza(
    crustSize: CrustSize,
    crustType: CrustType,
    toppings: Seq[Topping]
)

// create and use Pizza instances
val p1 = Pizza(Small, Thin, Seq(Cheese))
val p2 = p1.copy(
    toppings = p1.toppings ++ Seq(Mushrooms, Olives)
)
val p3 = p2.copy(crustSize = Large)

Update: All of my new videos are now on
LearnScala.dev