Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Scala 2.10 reflection how can I list the values of Enumeration?

Having a following enumeration

object ResponseType extends Enumeration {
  val Listing, Album = Value
}

How do I get a list of its vals?

like image 931
Nikita Volkov Avatar asked Aug 26 '12 09:08

Nikita Volkov


1 Answers

If you want to be thorough about this, you need to check that your symbols have Value as a supertype:

def valueSymbols[E <: Enumeration: TypeTag] = {
  val valueType = typeOf[E#Value]
  typeOf[E].members.filter(sym => !sym.isMethod &&
    sym.typeSignature.baseType(valueType.typeSymbol) =:= valueType
  )
}

Now even if you have the following (which is perfectly legal):

object ResponseType extends Enumeration {
  val Listing, Album = Value
  val someNonValueThing = "You don't want this in your list of value symbols!"
}

You still get the correct answer:

scala> valueSymbols[ResponseType.type] foreach println
value Album
value Listing

Your current approach would include value someNonValueThing here.

like image 151
Travis Brown Avatar answered Sep 18 '22 13:09

Travis Brown