我隔壁班的結構:宏擴展在派生類
trait SomeType
trait Root {
val allMySomeTypes: Seq[SomeType]
}
class Child extends Root {
object MyType1 extends SomeType {...}
object MyType2 extends SomeType {...}
}
我想初始化VAL allMySomeTypes如延長混凝土類中定義SOMETYPE所有對象的序列。因此對於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類中額外鍵入而不使用運行時反射的情況下構建實際成員的Seq嗎?
謝謝你這麼完整和解釋的答案!我將仔細研究宏註釋。 – newf