Search code examples
scalareflectiontypesruntimescala-reflect

Get parent Enumeration of Value typetag


I have a Type instance that refers to the Value of a specific Enumeration.

Is there any way to get the Type or Symbol of the parent enum? In other words, if I have typeOf[SomeEnumeration.Value] how can I obtain typeOf[SomeEnumeration]?

I know this information exists at runtime because I can see it in the debug console with valueType.pre.sym, but I can't come up with a public API for accessing it in code.

My first thought was valueType.typeSymbol.owner, but this just gives the Symbol for the base class Enumeration, not the specific enumeration instance that I want.


Solution

  • Suppose you have an enumeration

    object WeekDay extends Enumeration {
      type WeekDay = Value
      val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
    }
    

    Then try to match against TypeRef

    import scala.reflect.runtime.universe._
    
    typeOf[WeekDay.Value] match {
      case TypeRef(pre, _, _) => pre // WeekDay.type
    }