Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Enum

Exercises

Scala 3 introduces enums as a first-class feature to define a group of named values. Enums are a significant improvement over Scala 2's sealed trait and case object pattern for enumerations, providing a cleaner syntax and more functionality. Here are some exercises to help you understand and practice using enums in Scala 3.

Exercise 1: Basic Enum

Task: Define an enum DayOfWeek representing the days of the week. Then, write a function isWeekend that takes a DayOfWeek and returns true if it's either Saturday or Sunday, and false otherwise.

Exercise 2: Enum with Parameters

Task: Define an enum TrafficLight where each value can have a color name as a String parameter. Implement a method color that returns the color of the traffic light.

Exercise 3: Enums in Collections

Task: Given a list of TrafficLight enums, write a function that counts how many of each light are in the list and prints the result.