I would like to add a method to scala.Enumeration. My first approach was to try to extend it, but was bitten by this. My second approach was to try to define a method, and pass in the Enumeration - if that worked, I hoped to use an implicit conversion. I'm having a hard time preserving type with the return type of the method, however.
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)
}
}
One obvious fix would be to just remove the return type declaration from the parse method, but that gives me a "illegal dependent method type". This leaves me with lots of questions:
Is this possible to specify? One way or another, I'd like to get a nice error message when parsing an enumeration field in from a String.
Why do I get the "illegal dependent method type"?
What precisely is the "#" operator(?) in this case?