Can reflection be used to find the actual type of field declared by the Scala Enumeration subtype?

I want to automatically convert / force strings to Scala enumeration values, but not knowing in advance what subclasses of Enumeration (subobject?) Are from the declaration.

So, considering:

object MyEnumeration extends Enumeration { type MyEnumeration = Value val FirstValue, SecondValue = Value } 

and

 class MyThing { import MyEnumeration._ var whichOne: MyEnumeration = FirstValue } 

how to implement the following?

 val myThing = new MyThing() setByReflection(myThing, "whichOne", "SecondValue") 

What I find is that when I get the MyThing.whichOne class (via java.lang.Field), return is "scala.Enumeration $ Value", which is not enough for me to list the names of all possible values.

+4
source share
2 answers

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" ) 
+1
source

Mark

0
source

Source: https://habr.com/ru/post/1384505/


All Articles