Scala 缺少scodec.Codec[Command]隐式,因为类具有非值字段
我试图在现有的项目中使用鉴别器,我想我的类可能有问题 想想这个。如果我将Scala 缺少scodec.Codec[Command]隐式,因为类具有非值字段,scala,shapeless,scodec,Scala,Shapeless,Scodec,我试图在现有的项目中使用鉴别器,我想我的类可能有问题 想想这个。如果我将左转及其编解码器更改为 sealed class TurnLeft(degrees: Int) extends Command { def getDegrees: Int = degrees } implicit val leftCodec: Codec[TurnLeft] = uint8or16.xmap[TurnLeft](v => new TurnLeft(v), _.getDegrees) 我明白了 如果
左转
及其编解码器更改为
sealed class TurnLeft(degrees: Int) extends Command {
def getDegrees: Int = degrees
}
implicit val leftCodec: Codec[TurnLeft] = uint8or16.xmap[TurnLeft](v => new TurnLeft(v), _.getDegrees)
我明白了
如果我设置度
字段值字段,这一切都可以正常工作。我怀疑这是一件很棘手的事。我该怎么做才能让它工作
演示该问题的示例项目是。shapeless的
Generic
是为“case-class-like”类型定义的。在第一种近似情况下,类case类型的值可以解构为它的构造函数参数,然后这些参数可以用来重构一个相等的值,即
case class Foo ...
val foo = Foo(...)
val fooGen = Generic[Foo]
assert(fooGen.from(fooGen.to(foo)) == foo)
具有单个构造函数参数列表的Case类符合此标准,而其构造函数参数没有public(lazy)vals的类,或带有匹配的apply
/unapply
的类则不符合此标准
Generic
的实现是相当允许的,并且将对应于构造函数参数(按类型和顺序)的(惰性)val成员视为等同于可访问的构造函数参数,因此我们可以得到的最接近您的示例如下:
sealed class TurnLeft(degrees: Int) extends Command {
val getDegrees: Int = degrees
}
scala> Generic[TurnLeft]
res0: shapeless.Generic[TurnLeft]{type Repr = Int :: HNil } = ...
在这种情况下,
getDegrees
被视为单个Int
构造函数参数的访问器。Awesome!谢谢,迈尔斯。关于这件事的附带问题。这些val的定义会使给定类的内存占用加倍吗?这里只有一个val:非case类的构造函数参数不会生成val,除非它被显式标记为val。我明白了。我假设如果def getDegrees
可以返回它,它仍然必须存储在某个地方。
sealed class TurnLeft(degrees: Int) extends Command {
val getDegrees: Int = degrees
}
scala> Generic[TurnLeft]
res0: shapeless.Generic[TurnLeft]{type Repr = Int :: HNil } = ...