简体   繁体   English

从类型中获取TypeTag?

[英]Get a TypeTag from a Type?

I can get a Type from a TypeTag[A] by using the tpe method. 我可以使用tpe方法从TypeTag[A]获取Type But can I also recover the type-tag from a type? 但我还可以从类型中恢复类型标记吗?

import scala.reflect.runtime.{universe => ru}
import ru.{Type, TypeTag}

def forward[A](implicit tt: TypeTag[A]): Type = tt.tpe

def backward(t: Type): TypeTag[_] = ???

The reason being that I have an API that uses type-tags as keys into a map, but at some point I only have the type and dropped the tag. 原因是我有一个API使用类型标签作为地图的键,但在某些时候我只有类型并删除了标签。

It is possible: 有可能的:

import scala.reflect.runtime.universe._
import scala.reflect.api

val mirror = runtimeMirror(getClass.getClassLoader)  // whatever mirror you use to obtain the `Type`

def backward[T](tpe: Type): TypeTag[T] =
  TypeTag(mirror, new api.TypeCreator {
    def apply[U <: api.Universe with Singleton](m: api.Mirror[U]) =
      if (m eq mirror) tpe.asInstanceOf[U # Type]
      else throw new IllegalArgumentException(s"Type tag defined in $mirror cannot be migrated to other mirrors.")
  })

assert(backward[String](forward[String]) == typeTag[String])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM