Scala 如何对泛型类型中包含的类型变量进行大小写匹配?
我正在编写一个Scala子例程来构造一个TypeTag[Map[\up>这将简化为从一个Scala 如何对泛型类型中包含的类型变量进行大小写匹配?,scala,reflection,pattern-matching,Scala,Reflection,Pattern Matching,我正在编写一个Scala子例程来构造一个TypeTag[Map[\up>这将简化为从一个TypeTag[Iterable[t1]获取一个TypeTag[t1]。这是可能的,但非常难看: 因此,您最终会得到类似(未经测试!)的结果: 导入scala.reflect.runtime.universe_ def typeToTypeTag[T]( tpe:类型, 镜像:reflect.api.mirror[reflect.runtime.universe.type] ):TypeTag[T]={ Ty
TypeTag[Iterable[t1]
获取一个TypeTag[t1]
。这是可能的,但非常难看:
因此,您最终会得到类似(未经测试!)的结果:
导入scala.reflect.runtime.universe_
def typeToTypeTag[T](
tpe:类型,
镜像:reflect.api.mirror[reflect.runtime.universe.type]
):TypeTag[T]={
TypeTag(镜像,新reflect.api.TypeCreator{
def应用[U]
隐式val t1=argTypeTag[t1](tt1)
隐式val t2=argTypeTag[t2](tt2)
typeTag[Map[t1,t2]]
}
这将简化为从类型标签[Iterable[t1]]
获取类型标签[t1]
。这是可能的,但非常难看:
因此,您最终会得到类似(未经测试!)的结果:
导入scala.reflect.runtime.universe_
def typeToTypeTag[T](
tpe:类型,
镜像:reflect.api.mirror[reflect.runtime.universe.type]
):TypeTag[T]={
TypeTag(镜像,新reflect.api.TypeCreator{
def应用[U]
隐式val t1=argTypeTag[t1](tt1)
隐式val t2=argTypeTag[t2](tt2)
typeTag[Map[t1,t2]]
}
tag1: TypeTag[Iterable[_<: A]]
tag2: TypeTag[Iterable[_<: B]]
(tag1, tag2) match {
case (tt1: TypeTag[Iterable[t1]], tt2: TypeTag[Iterable[t2]]) =>
implicit val t1 = tt1
implicit val t2 = tt2
ScalaReflection.universe.typeTag[Map[t1, t2]]
}
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]
}
})
}
def argTypeTag[A](tag: TypeTag[_ /* Actually F[A] for some F */]): TypeTag[A] =
typeToTypeTag[A](tag.tpe.typeArgs.head)
(tag1, tag2) match {
case (tt1: TypeTag[Iterable[t1]], tt2: TypeTag[Iterable[t2]]) =>
implicit val t1 = argTypeTag[t1](tt1)
implicit val t2 = argTypeTag[t2](tt2)
typeTag[Map[t1, t2]]
}