我想向scala.Enumeration添加一個方法。我的第一個方法是試圖擴展它,但被this咬了。我的第二種方法是嘗試定義一個方法,並傳入枚舉 - 如果這有效,我希望使用隱式轉換。然而,我很難用保留類型的方法返回類型。引用方法簽名中的枚舉值類型
object EnumExample {
object SampleEnum extends Enumeration {
val include, exclude = Value
}
def parse[T <: Enumeration](name:String, enum:T):T#Value =
enum.valueOf(name) match {
case Some(x) => x
case x => throw new RuntimeException("No field named '" + name + "' found on enum " + enum + ", legal values = " + enum.values)
}
def main(args:Array[String]) = {
//compiles fine, and preserves custom type
val withNameExample:SampleEnum.Value = SampleEnum.withName("include")
//also fine, but we lost type info
val enumWithHash:Enumeration#Value = parse("include", SampleEnum)
/**
error: type mismatch;
found : Main.$anon.EnumExample.SampleEnum#Value
required: Main.$anon.EnumExample.SampleEnum.Value
val parseExample:SampleEnum.Value = parse("include", SampleEnum)
*
*/
val customTypeWithHash:SampleEnum.type#Value = parse("include", SampleEnum)
//same error
val customTypeWithDot:SampleEnum.Value = parse("include", SampleEnum)
}
}
一個明顯的問題是隻從parse方法中刪除返回類型聲明,但這給了我一個「非法依賴方法類型」。這給我留下了很多問題:
這是可以指定?不管怎樣,我想在從字符串中解析枚舉字段時得到一個很好的錯誤信息。
爲什麼我會得到「非法依賴方法類型」?
在這種情況下,「#」運算符(?)究竟是什麼?
碰到這個問題,試過了,但是我在'enum.valueOf(name)match {'說'value的valueOf不是類型參數T的成員'的編譯錯誤。那麼爲什麼這樣呢?我使用Scala 2.9.1。 – zapadlo 2013-01-07 10:15:02
我認爲他們在2.9中刪除了valueOf - 用withName代替。更好的是,我推薦這裏描述的密封traits /案例對象:http://stackoverflow.com/questions/4236251/should-i-prefer-sealed-class-or-enumeration-in-scala。這種方法有它自己的疣,但根據我的經驗,它更有用。 – 2013-01-07 12:57:29