【发布时间】:2014-01-17 19:59:40
【问题描述】:
我有下一个班级结构:
trait SomeType
trait Root {
val allMySomeTypes: Seq[SomeType]
}
class Child extends Root {
object MyType1 extends SomeType {...}
object MyType2 extends SomeType {...}
}
并且我想将 val allMySomeTypes 初始化为扩展具体类中定义的 SomeType 的所有对象的 Seq。所以对于 Child 实例,它将是 val allMySomeTypes: Seq[SomeType] = Seq(MyType1, MyType2)。
我编写了一个宏来查找具有某种基本类型的对象:
def getMembersOfCurrentByType_impl[S](c: Context)(implicit ev: c.WeakTypeTag[S]) = {
import c.universe._
val seqApply = Select(reify(Seq).tree, newTermName("apply"))
val objs = c.enclosingClass.symbol.typeSignature.declarations.collect {
case o: ModuleSymbol if o.typeSignature <:< ev.tpe => Ident(o) //Select(c.prefix.tree, o)
}.toList
c.Expr[Seq[S]] {Apply(seqApply, objs)}
}
并将其绑定到
trait Root {
val allMySomeTypes: Seq[SomeType] = macro getMembersOfCurrentByType_impl[SomeType]
}
但是,很明显,由于基本特征的宏扩展,我在 Child 类中有 Empty 序列。 我可以构建实际成员的 Seq,而无需在 Child 类中额外键入且不使用运行时反射吗?
【问题讨论】:
标签: scala scala-macros