A particular type is lost at runtime, but you can capture it at compile time through implicits . You can specify the implicit in your listing, as shown below.
object MyEnumeration extends Enumeration { type MyEnumeration = Value val FirstValue, SecondValue = Value implicit def convertMyEnumeration( value: String ) = MyEnumeration.withName( value ) } class MyThing { import MyEnumeration._ var whichOne: MyEnumeration = FirstValue } val myThing = new MyThing() myThing.whichOne = "SecondValue"
You can also do the following if the type system cannot allow your enumeration to apply the correct implicit in your customs, which you can use by default when using polymorphism , and provide a setter, as shown below:
class MySuperThing { def setWhichOne( value: String } } class MyThing extends MySuperThing { import MyEnumeration._ var whichOne: MyEnumeration = FirstValue def setWhichOne( value: String ) = MyEnumeration.withName( value ) } val myThing: MySuperThing = new MyThing() myThing.setWhichOne( "SecondValue" )
source share