问题描述
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
非常感谢您的意见。
解决方法
我猜你知道 scala.ValueOf
和 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
}
如果您想避免像 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? 中的隐式参数,同样不清楚目标是什么。