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

Exercise 1: Basic Enum

enum DayOfWeek:
  case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

def isWeekend(day: DayOfWeek): Boolean = day match
  case DayOfWeek.Saturday | DayOfWeek.Sunday => true
  case _ => false

// Test your function
println(isWeekend(DayOfWeek.Saturday)) // Output: true
println(isWeekend(DayOfWeek.Wednesday)) // Output: false

Exercise 2: Enum with Parameters

enum TrafficLight(val color: String):
  case Red extends TrafficLight("red")
  case Yellow extends TrafficLight("yellow")
  case Green extends TrafficLight("green")

// Test
println(TrafficLight.Red.color) // Output: red

Exercise 3: Enums in Collections

def countLights(lights: List[TrafficLight]): Unit =
  val counts = lights.groupBy(identity).view.mapValues(_.size).toMap
  println(counts)

// Test your function
val lights = List(TrafficLight.Red, TrafficLight.Yellow, TrafficLight.Red, TrafficLight.Green, TrafficLight.Yellow)
countLights(lights) // Output: Map(Red -> 2, Yellow -> 2, Green -> 1)