Scala Language Enumerations

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

Approach with sealed trait and case objects is preferred because Scala enumeration has a few problems:

  1. Enumerations have the same type after erasure.
  2. Compiler doesn't complain about “Match is not exhaustive", if case is missed it will fail in runtime scala.MatchError:
def isWeekendWithBug(day: WeekDays.Value): Boolean = day match {
  case WeekDays.Sun | WeekDays.Sat => true
}

isWeekendWithBug(WeekDays.Fri)
scala.MatchError: Fri (of class scala.Enumeration$Val)

Compare with:

def isWeekendWithBug(day: WeekDay): Boolean = day match {
  case WeekDay.Sun | WeekDay.Sat => true
}

Warning: match may not be exhaustive.
It would fail on the following inputs: Fri, Mon, Thu, Tue, Wed
def isWeekendWithBug(day: WeekDay): Boolean = day match {
                                          ^

More detailed explanation is presented in this article about Scala Enumeration.



Got any Scala Language Question?