Matching with subclasses in macro

I need to convert the string value to the actual type, so I decided to try a macro path for this. I have several data types:

sealed abstract class Tag(val name: String)
case object Case1 extends Tag("case1")
case object Case2 extends Tag("case2")
case object Case3 extends Tag("case3")
etc...

I want to write a simple resolver:

val tag: Tag = TagResolver.fromString("case2")

This string should return Case2accordingly. I am a manager to do the following:

def typeFromString(c: Context)(name: c.Expr[String]): c.Expr[Tag] = {
    import c.universe._
    val tag = typeTag[Tag]
    val accSymb = tag.tpe.typeSymbol.asClass
    val subclasses = accSymb.knownDirectSubclasses // all my cases

    subclasses.map { sub =>
      val name = sub.typeSignature.member(newTermName("name")).asMethod // name field
      ???
    }
  }

But how can I match the name: c.Expr[String]field value name, and if the match returns the corresponding tag?

+4
source share
1 answer

I don’t think there is a reliable way to do this because knownDirectSubclasses can refer to classes that have not yet been compiled, so we cannot evaluate them.

, , ( API Symbol.annotations). , , knownDirectSubclasses : https://issues.scala-lang.org/browse/SI-7046.

+1

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


All Articles