枚举
使用 sealed trait
和 case objects
的方法是首选,因为 Scala 枚举有一些问题:
- 擦除后枚举具有相同的类型。
- 编译器没有抱怨匹配并不详尽,如果错过了它将在运行时失败 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 的文章中提供了更详细的说明。