【问题标题】:In scala, is it possible to initialise a singleton object from a TypeTag?在 scala 中,是否可以从 TypeTag 初始化单例对象?
【发布时间】:2021-06-20 21:41:25
【问题描述】:

假设我有一个带有 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 反射中原生提供。因此,请尽可能建议任何库/hack,而不要更改类的签名TypeViz

非常感谢您的意见。

【问题讨论】:

  • 什么是.typeView

标签: scala dependent-type path-dependent-type singleton-type scala-2.13


【解决方案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
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多