我试图在现有的项目中使用鉴别器,但我猜我的类出了问题。
考虑一下这个scodec example。如果我将TurnLeft
及其编解码器更改为
sealed class TurnLeft(degrees: Int) extends Command {
def getDegrees: Int = degrees
}
implicit val leftCodec: Codec[TurnLeft] = uint8or16.xmap[TurnLeft](v => new TurnLeft(v), _.getDegrees)
我得到了
Error:(x, x) could not find Lazy implicit value of type scodec.Codec[Command]
val codec: Codec[Either[UnrecognizedCommand, Command]] = discriminatorFallback(unrecognizedCodec, Codec[Command])
如果我让degrees
字段值字段,这一切都会起作用。我怀疑这是无形体的一些棘手问题。我该怎么做才能让它工作呢?
演示此问题的示例项目是here。
发布于 2017-02-06 18:21:54
shapeless的Generic
是为"case-class-like“类型定义的。在第一次近似中,类case类型的值可以被解构为它的构造函数参数,然后这些参数可以用来重构一个相等的值,即。
case class Foo ...
val foo = Foo(...)
val fooGen = Generic[Foo]
assert(fooGen.from(fooGen.to(foo)) == foo)
只有一个构造函数参数列表的Case类符合这个标准,而没有构造函数参数的公共(惰性)定义的类,或者具有匹配的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
构造函数参数的访问器。
https://stackoverflow.com/questions/41997534
复制相似问题