gpt4 book ai didi

scala - 标记案例类上的 LabelledGeneric 实例生成使我在无形中产生错误

转载 作者:行者123 更新时间:2023-12-01 19:35:02 26 4
gpt4 key购买 nike

我试图从来自另一个 HList(确切地说是另一个 LabelledGeneric)的标记类型中获取 LabelledGeneric 实例,但是编译器给我一个错误,说它找不到隐式。

确切的错误是(启用 -x-log-implicits):

shapeless.this.DefaultSymbolicLabelling.mkDefaultSymbolicLabelling is not a valid implicit value for shapeless.DefaultSymbolicLabelling.Aux[Inner with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("c")],Inner],K] because:
hasMatchingSymbol reported error: Inner with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("c")],Inner] is not case class like or the root of a sealed family of types

这是片段:
case class Inner(a: Int)
case class Outer(b: Int, c: Inner)

val gen = LabelledGeneric[Outer]

val inner = Inner(1)
val outer = Outer(2, inner)

def getGen[A, L](x: A)(implicit gen: LabelledGeneric.Aux[A, L]) = gen

val hOuter = gen.to(outer)

getGen(hOuter.at(1))

我在这里遗漏了一些明显的东西吗?

谢谢。

编辑:

我添加了案例类的定义。我也在使用 Scala 2.11.8 和 shapeless 2.3.0

最佳答案

LabelledGeneric[Outer]采用 Outer 类型的值到无形的记录上。这些是 HList s 的字段,每个字段都是一个标记有“标签”的值……一个与案例类中的字段名称相对应的单例类型。类型为 T 的标记值是类型 T 的子类型,但这两种类型并不相同。通常这绝对没问题。

在您的场景中,您正在从事该领域 hOuter.at(1)类型为 FieldType['c.type, Inner] .这是一个类型别名,扩展为以下一口,

Inner with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("c")],Inner]

然后你要求 LabelledGeneric对应于该类型的实例。不幸的是,虽然有一个 LabelledGeneric Inner 的实例,没有 FieldType['c.type, Inner] 的实例,因为,正如编译器错误消息所说(写扩展类型),
Inner with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("c")],Inner]
is not case class like or the root of a sealed family of types

如果您实际上没有将标签用于任何事情,那么最简单的解决方法是使用 Generic而不是 LabelledGeneric贯穿始终,或至少在 gen 的定义中.

如果您正在使用标签,那么解决您的问题的方法是将它们从字段中剥离。最简单的方法是依赖 Inner,在这里可行但不能概括。是 FieldType['c.type, Inner] 的子类型并使用类型归属,
getGen(hOuter.at(1): Inner)

这意味着类型参数 AgetGen将被推断为 Inner以及对 LabelledGeneric[A] 的隐式查找将会成功。

更通用的解决方案是使用 shapeless 的 Values type 类采用无形的记录并从其每个元素上剥离标签,产生 HList仅由值组成。

关于scala - 标记案例类上的 LabelledGeneric 实例生成使我在无形中产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36344135/

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