scala 中的运行时枚举描述

Runtime enum description in scala

我正在寻找 Scala 中的枚举,它提供了依赖于运行时的选项之一的描述。

例如,一个 Answer 枚举,它允许用户在指定某些消息时回答 yes/no 以及其他。

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 和 returns 和 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