Scala中的运行时枚举描述



我正在寻找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

有可能吗?还是我宁愿实施案例类的层次结构?

您可以将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

最新更新