【问题标题】:In Scala, What is the difference between universe.TypeTag, TypeRef, and Type?在 Scala 中,universe.TypeTag、TypeRef 和 Type 有什么区别?
【发布时间】:2016-06-05 16:43:33
【问题描述】:

有 3 个不同的类都绑定到一个 Universe:TypeTagTypeRefType。为什么我们需要全部 3 个?如果我只有Type,如何将其转换为TypeTagTypeRef

例如我通过 Scala 反射 API 函数获得了一个通用的超类型:

val at = ...some TypeTag...
val bt = ...some TypeTag...

val tpe = ScalaReflection.universe.lub(List(at.tpe, bt.tpe))
ScalaReflection.universe.(tpe)

如何将其转换为TypeTagTypeRef

【问题讨论】:

    标签: scala dynamic scala-reflect


    【解决方案1】:

    TypeRefType的特例:

    abstract type TypeRef >: Null <: Universe.TypeRefApi with Universe.Type 
    

    您可以通过模式匹配检查Type 是否实际上是TypeRef

    tpe match {
      case TypeRef(prefix, sym, args) =>
      // or alternately
      case typeRef: TypeRef =>
    }
    

    TypeTag[A] 是一种访问Type 的方法,其中 1) 适用于不同的镜像; 2) 可以由编译器从类型参数中自动生成(注意Type 不是通用的)。

    Type 转换为TypeTag,从How to create a TypeTag manually?

    import scala.reflect.runtime.universe._
    
    def typeToTypeTag[T](
      tpe: Type,
      mirror: reflect.api.Mirror[reflect.runtime.universe.type]
    ): TypeTag[T] = {
      TypeTag(mirror, new reflect.api.TypeCreator {
        def apply[U <: reflect.api.Universe with Singleton](m: reflect.api.Mirror[U]) = {
          assert(m eq mirror, s"TypeTag[$tpe] defined in $mirror cannot be migrated to $m.")
          tpe.asInstanceOf[U#Type]
        }
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-06
      相关资源
      最近更新 更多