gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 06:01:02 25 4
gpt4 key购买 nike

假设我有一个带有 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? 这样的隐式参数,同样不清楚目标是什么。

关于scala - 在 scala 中,是否可以从 TypeTag 初始化单例对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67353632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com