dimanche 17 février 2019

How can I create an Option type at runtime (reflection)?

Using reflection, I have determined the runtime type of a thing, t: Type. Now I want to create a new Type of Option[t]. How can I do that?

val t: Type = ...
val optT: Type = ???  // Option of whatever t is

Why I want this: I have a handler function that operates on a Type. At compile time I have something like this:

trait Thing { name: String }
case class BigThing(name: String) extends Thing

case class Stuff[T <: Thing]( id: Int, maybeThing: Option[T] ) // contrived

def handler( t: Type ): Output = {...}

I can reflect that if I have a class of type Stuff, it has a member maybeThing of type Object[T] or even Object[Thing]. At runtime let's say I can determine that a specific object has T = BigThing, so I want to pass Option[BigThing], not Option[T] or Option[Thing] to handler(). That's why I'm trying to create a runtime type of Option[BigThing].

I did try the following but Scala didn't like it:

val newType = staticClass(s"Option[${runtimeTypeTAsString}]")





Aucun commentaire:

Enregistrer un commentaire