我刚刚开始使用typelevel的“scodec”库:https://github.com/scodec/scodec
我发现我一直在使用以下功能:
/**
* When called on a `Codec[L]` for some `L <: HList`, returns a new codec that encodes/decodes
* `B :: L` but only returns `L`. HList equivalent of `~>`.
* @group hlist
*/
def :~>:[B](codec: Codec[B])(implicit ev: Unit =:= B): Codec[L] = codec.dropLeft(self)
如果我有一个我不想使用规范的每个值的案例类,这很有用:
case class Example(value1: Int, value3)
implicit val exampleCodec: Codec[Example] = (
("value1" | uint8) ::
("value2" | uint8) :~>: // decode/encode, but dont pass this in when converting from hlist to case class
("value3" | uint8)
).as[Example]
如果我想忽略的值不是hlist中的最后一个值,那么这很有效。有人知道如何更改编解码器,如果相反,我希望我的案例类是:
case class Example(value1:Int,value2:Int)// ignore value3
感谢任何帮助 - 谢谢!
答案 0 :(得分:3)
您可以使用<~
,而不是:
implicit val exampleCodec: Codec[Example] = (
("value1" | uint8) ::
("value2" | uint8).unit(0) :~>:
("value3" | uint8)
).as[Example]
你写的是:
implicit val exampleCodec: Codec[Example] = (
("value1" | uint8) ::
("value3" | uint8) <~
("value2" | uint8).unit(0)
).as[Example]
请注意,您明确必须将编解码器设为Codec[Unit]
- 我在此处使用.unit(0)
为例。