列舉

使用 sealed traitcase objects 的方法是首選,因為 Scala 列舉有一些問題:

  1. 擦除後列舉具有相同的型別。
  2. 編譯器沒有抱怨匹配並不詳盡,如果錯過了它將在執行時失敗 3:
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)

與之比較:

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 {
                                          ^

有關 Scala Enumeration 的文章中提供了更詳細的說明。