I'd like to dynamically insert a type parameter, i.e. List[T]
, where T can only be found at run-time.
Normally you can create bindings like this if you already have an existing type parameter T
(not the case), or during run-time using TypeTag
s.
The latter sounds like the way to go, but this shifts the question to "how do I get my TypeTag here".
I know how to create a TypeTag using if you have your type T
(typeTag[T]
), or if you have an instance of your type T
(see getTypeTag
below).
However, I have neither; what I do have of my type in question is a reflect.runtime.universe.Type
. Might it be possible to convert this into a TypeTag
so I can dynamically insert my type parameter?
Bonus points if the List
can be made dynamic as well.
scala> import scala.reflect.runtime.{universe => ru}
scala> def getTypeTag[T: ru.TypeTag](obj: T) = ru.typeTag[T]
scala> def insertTag[T](tt: ru.TypeTag[T]) = List[T]_
scala> val fn = (a: String) => "foo"
fn: String => String = <function1>
scala> val pars = getTypeTag(fn).tpe.typeArgs.init(0)
pars: reflect.runtime.universe.Type = String
scala> insertTag(pars)
<console>:21: error: type mismatch;
found : reflect.runtime.universe.Type
required: reflect.runtime.universe.TypeTag[?]
insertTag(pars)
^
Aucun commentaire:
Enregistrer un commentaire