在 Scala 中,是否可以从 TypeTag 初始化单例对象?

问题描述

假设我有一个带有 TypeTag 的类:

case class TypeViz[T : TypeTag]() {

  def getonlyInstance = ...
}

如果 T 是单例类型,是否可以在运行时使用 TypeTag 来查找 T 的值?即:


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)
    }

我不确定这个特性是否在 Scala 反射中原生提供。因此,请尽可能在不更改类 TypeViz

的签名的情况下建议任何库/hack

非常感谢您的意见。

解决方法

我猜你知道 scala.ValueOfshapeless.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
}

如果您想避免像 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? 中的隐式参数,同样不清楚目标是什么。