2015-01-11 11 views
8

È possibile ottenere uno Type da un TypeTag[A] utilizzando il metodo tpe. Ma posso anche recuperare il tag di tipo da un tipo?Ottieni un TypeTag da un tipo?

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[_] = ??? 

Il motivo è che ho un'API che utilizza tipo-tag come chiavi in ​​una mappa, ma ad un certo punto ho solo il tipo e lasciò cadere il tag.

+1

rilevanti, eventualmente duplicate: http://stackoverflow.com/questions/11494788/how-to-create-a-typetag-manually –

+0

api cambiato ora - in modo da poter passare l'implementazione di 'TypeCreator' invece di' TypeFactory' – dk14

risposta

7

E 'possibile:

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

da dove provengono 'TypeCreator',' api' e 'Universe'? –

+0

Siamo spiacenti! Ho aggiornato la risposta. –

+0

Grazie, funziona! –

Problemi correlati