CodexBloom - Programming Q&A Platform

How to handle non-exhaustive pattern matching in Scala 3 with enums?

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
scala enums pattern-matching scala3 Scala

I'm building a feature where I can't seem to get I'm sure I'm missing something obvious here, but I tried several approaches but none seem to work. I'm working with Scala 3 and using enums to represent different states in my application. However, I'm working with a non-exhaustive pattern matching warning when I try to match on the enum cases. Here's the enum definition along with my matching code: ```scala enum TrafficLight: case Red, Yellow, Green def nextLight(light: TrafficLight): TrafficLight = light match { case TrafficLight.Red => TrafficLight.Green case TrafficLight.Green => TrafficLight.Yellow // Missing case for Yellow } ``` When I compile this code, I get a warning about non-exhaustive pattern matching. I've tried adding a catch-all case like this: ```scala case _ => light ``` But it feels wrong to handle it that way since I want to manage the states explicitly. What's the best practice to avoid this warning while ensuring that all cases of the enum are handled? Additionally, is there a way to make the compiler enforce that all cases must be matched? I also want to ensure that if I add a new enum case in the future, I get a compile-time behavior if I forget to handle it. Any insights would be appreciated! My development environment is macOS. Has anyone else encountered this? How would you solve this? I'm working on a desktop app that needs to handle this. I recently upgraded to Scala 3.10.