0

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}]")
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Greg
  • 10,696
  • 22
  • 68
  • 98

1 Answers1

2

According to tutorial

there are three ways to instantiate a Type.

  • via method typeOf on scala.reflect.api.TypeTags, which is mixed into Universe (simplest and most common).
  • Standard Types, such as Int, Boolean, Any, or Unit are accessible through the available universe.
  • Manual instantiation using factory methods such as typeRef or polyType on scala.reflect.api.Types, (not recommended).

Using the third way,

import scala.reflect.runtime.universe._

class MyClass

val t: Type = typeOf[MyClass] //pckg.App.MyClass

val mirror = runtimeMirror(ClassLoader.getSystemClassLoader)

val optT: Type = mirror.universe.internal.typeRef(
  definitions.PredefModule.typeSignature, 
  definitions.OptionClass, 
  List(t)
) // Option[pckg.App.MyClass]

val optT1 : Type = typeOf[Option[MyClass]]

optT =:= optT1 // true
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66