scalareflectionscala-macroscase-classscala-2.11

Detect case class in scala macro


Within a method being called as a scala (2.11) macro, is there a way to programmatically determine whether a Type is a case class or not?

The API for the method I'm working through boils down to this:

def typeIsCaseClass(c: Context)(targetType: c.universe.Type): Boolean = {
  // targetType "is case class?"
}

I'm open to altering the API if need be.


Solution

  • The symbols usually contain all the interesting information:

    def typeIsCaseClass(c: Context)(targetType: c.universe.Type): Boolean = {
      val sym = targetType.typeSymbol
      sym.isClass && sym.asClass.isCaseClass
    }