Scala中的丰富枚举

时间:2013-10-09 06:48:25

标签: scala enumeration

我正在寻找一种在Scala中实现丰富枚举的机制,就像在Java中为枚举添加抽象方法并在枚举实例中实现它们一样。

请注意,使用密封的trait和case对象不是解决方案,因为我无法迭代现有的case对象,除非我保留它们的列表,这对于更改非常脆弱(特别是其他那些不明白发生了什么的人)

2 个答案:

答案 0 :(得分:5)

只需展开Val

object items extends Enumeration {

  val pen = Item("writing")
  val brush = Item("painting")

  final case class Item(key: String) extends Val {
    def kind: String = toString
  }
}

object Test {
  import items._
  def main(args: Array[String]) {
    println(pen.kind +" is for "+ pen.key)
    println(brush.key)
    println(items.values)
  }
}

object days extends Enumeration {
  case class Day(i: Int, name: String) extends Val(i, name) {
    def isWeekDay = i < 5
  }
  private def newDay() = new Day(nextId, null)
  val Mon, Tue, Wed, Thu, Fri, Sat, Sun = newDay()
  val daysOfTheWeek = values.toList.asInstanceOf[List[Day]]
}

object Test extends App {
  import days._
  println(Thu)
  println(days.values.toList mkString ",")
  for (d <- days.daysOfTheWeek) Console println s"$d is weekday? ${d.isWeekDay}"
}

答案 1 :(得分:5)

另请查看Viktor Klang在此提出的建议:https://gist.github.com/viktorklang/1057513

构建枚举是一种非常安全的方法。