In scala, is it possible to initialise a singleton object from a TypeTag?

121 Views Asked by At

Assuming that I have a class with a TypeTag:

case class TypeViz[T : TypeTag]() {

  def getOnlyInstance = ...
}

Is it possible to use the TypeTag in runtime to find the value of T, if T is a singleton type? Namely:


object TypeViewsSpec {

  val a = 3

  val b = new Object {

    val c = 3
  }
}


    it("object") {

      val v = TypeViz[TypeViewsSpec.type]
      assert(v.getOnlyInstance == TypeViewsSpec)
    }

    it("constant") {

      val v = TypeViz[3].typeView
      assert(v.getOnlyInstance == 3)
    }

    it("unique value") {

      val v = TypeViz[TypeViewsSpec.a.type].typeView
      assert(v.getOnlyInstance == 3)
    }

    it(" ... more complex") {

      val v = TypeViz[TypeViewsSpec.b.c.type].typeView
      assert(v.getOnlyInstance == 3)
    }

I'm not sure if this feature is provided natively in scala reflection. So please suggest any library/hack whenever possible without changing the signature of the class TypeViz

Thanks a lot for your opinion.

1

There are 1 best solutions below

0
On

I guess you know about scala.ValueOf and shapeless.Witness

case class TypeViz[T : TypeTag]() {
  def getOnlyInstance(implicit valueOf: ValueOf[T]) = valueOf.value
}
case class TypeViz[T : TypeTag]() {
  def getOnlyInstance(implicit witness: Witness.Aux[T]) = witness.value
}

If you want to avoid implicit parameters like in In scala 2, can macro or any language feature be used to rewrite the abstract type reification mechanism in all subclasses? How about scala 3?, again it's not clear what the goal is.