Scala中的丰富枚举 [英] Rich enumeration in Scala
本文介绍了Scala中的丰富枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种在Scala中实现丰富枚举的机制,就像您在Java中将抽象方法添加到枚举并在枚举实例中实现它们的方式一样。
I am looking for a mechanism to implement rich enumerations in Scala, the same way you can in Java add abstract methods to enums and implement them in the instances of of the enum.
请注意,使用密封的特征和case对象不是解决方案,因为除非我保留它们的列表,否则我将无法遍历现有的case对象,这对更改非常脆弱(尤其是通过其他不了解发生了什么的人)
Please note that using a sealed trait and case objects is not a solution, because I would not be able to iterate over the existing case objects, unless I mantain a list of them, which is very fragile to changes (especially by other people who don't understand what's going on there)
推荐答案
只需扩展 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}"
}
这篇关于Scala中的丰富枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文