2

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

case class TypeViz[T : TypeTag]() {

  def getOnlyInstance = ...
}

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


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

非常感谢您的意见。

4

1 回答 1

1

我想你知道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
}

如果您想避免像在 scala 2 中那样的隐式参数,是否可以使用宏或任何语言特性来重写所有子类中的抽象类型具体化机制?斯卡拉 3 怎么样?,同样不清楚目标是什么。

于 2021-06-20T13:30:52.727 回答