2015-05-06 79 views
0

我正在尋找Scala中的enum,它提供了一個依賴於運行時的選項描述。運行時枚舉scala中的描述

例如,Answer enum,它允許用戶在指定某個消息時指定yes/no和other。

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 

這可能嗎?還是我應該實施一些層次的案例類?

回答

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