2015-01-11 3 views
8

tpe 방법을 사용하여 TypeTag[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[_] = ??? 

이유는지도에 키로 type-tags를 사용하는 API가 있기 때문입니다.하지만 어느 시점에서는 유형이있어 태그가 삭제되었습니다.

+1

관련, 가능성이 중복 : http://stackoverflow.com/questions/11494788/how-to-create-a-typetag-manually –

+0

API는 이제 변경 - 그래서 당신이 할 수있는 'TypeFactory' 대신에'TypeCreator' 구현체를 전달하십시오 – dk14

답변

7

것이 가능하다 :

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]) 
+0

'TypeCreator','api'와'Universe'는 어디서 온 것입니까? –

+0

죄송합니다! 답변을 업데이트했습니다. –

+0

감사합니다. 작동합니다! –