如何比较抽象的弱类型标签的无代表性泛型



我需要检查任何对象的类型并获取相应的对象。但是,无法通过将其传递到正常功能参数来解决。您需要比较直到所有类型参数匹配。

trait Wrap[T]
trait Interface
trait InterfaceA extends Interface
trait InterfaceB extends Interface
object InterfaceAImpl extends Wrap[InterfaceA] with Candidate
object InterfaceBImpl extends Wrap[InterfaceB] with Candidate
trait Mediate[T <: Interface] {
  val t: T = get[Wrap[T]]
}
object A extends Mediate[InterfaceA]
object B extends Mediate[InterfaceB]
def get[T: c.WeakTypeTag](c: blackbox.Context): c.Expr[Option[T]] = {
    import c.universe._
    // Find an object that mixes in a specific interface
    // Suppose that the result is [[object A]] and [[object B]]
    val detected: List[Symbol] = new CandidateExtractor[c.type](c).run[Candidate]
    // This result is
    // "InterfaceAImpl =:= Wrap[T]"
    // "InterfaceBImpl =:= Wrap[T]"
    // When called from A, it expects Wrap[InterfaceA] instead of Wrap[T]
    detected.foreach(x => println(s"${x.typeSignature} =:= ${weakTypeOf[T]}"))
    // Find objects that inherits Wrap [T] among objects that inherit a specific interface
    val r = detected.collectFirst {
      // Wrap[InterfaceA] and Wrap[T] are compared, so all false.
      case x if x.typeSignature =:= weakTypeOf[T] => x
    }
    c.Expr[Option[T]](
      q"$r"
    )
  }

是否有任何方法可以比较继承关系,包括通用关系?






第二次尝试

结果,我想做的是...

  1. object At: T = InterfaceAImpl,因为它继承了Wrap[InterfaceA]
  2. object B's t: T = InterfaceBImpl,因为它继承了 Wrap[InterfaceB]

所以<:<(typeOf[Wrap[_])无效。
必须是<:<(Wrap[_])
baseClasses.find(Wrap[_]).typeArgs.contains(T (is InterfaceA or InterfaceB))

尝试

List(typeOf[Wrap[_]].typeSymbol, typeOf[Candidate].typeSymbol).forall(x.typeSignature.baseClasses.contains)

List(typeOf[Wrap[_]].typeSymbol, typeOf[Candidate].typeSymbol).forall(x.typeSignature.baseType(_) match { case _ : TypeRef => true; case NoType => false })

最新更新