Note that there are some explanatory texts on larger screens.

plurals
  1. POReferring to a Enumeration Value type in a method signature
    primarykey
    data
    text
    <p>I would like to add a method to scala.Enumeration. My first approach was to try to extend it, but was bitten by <a href="https://stackoverflow.com/questions/1938309/how-to-add-a-method-to-a-scala-enumeration-object">this</a>. 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.</p> <pre><code>object EnumExample { object SampleEnum extends Enumeration { val include, exclude = Value } def parse[T &lt;: Enumeration](name:String, enum:T):T#Value = enum.valueOf(name) match { case Some(x) =&gt; x case x =&gt; 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) } } </code></pre> <p>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:</p> <ol> <li><p>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.</p></li> <li><p>Why do I get the "illegal dependent method type"?</p></li> <li><p>What precisely is the "#" operator(?) in this case?</p></li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload