我正在寻找Scala中的枚举,它提供了一个依赖于运行时的选项的描述。
例如,一个答案枚举,允许用户在指定某些消息时同时使用是/否以及其他消息。
object Answer extends Enumeration {
type Answer = Value
val Yes = Value("yes")
val No = Value("no")
val Other = ???
def apply(id: Int, msg: String = null) = {
id match {
case 0 => Yes
case 1 => No
case _ => Other(msg) ???
}
}
}
用法如下:
> Answer(0)
Yes
> Answer(1)
No
> Answer(2, "hey")
hey
> Answer(2, "hello")
hello
有可能吗?或者我应该实现一些案例类的层次结构?
答案 0 :(得分:2)
您可以将Other
定义为一个String
并返回Value
的函数:
object Answer extends Enumeration {
type Answer = Value
val Yes = Value("yes")
val No = Value("no")
val Other = (s:String) => Value(s)
def apply(id: Int, msg: String = null) = {
id match {
case 0 => Yes
case 1 => No
case _ => Other(msg)
}
}
}
然后您可以将其用作:
scala> Answer(0)
res0: Answer.Value = yes
scala> Answer(2, "hello")
res1: Answer.Value = hello
scala> Answer(2, "World")
res2: Answer.Value = World