[英]scodec ignore last value in codec conversion between hlist and case class
I'm just starting out with typelevel's "scodec" library: https://github.com/scodec/scodec 我刚开始使用typelevel的“scodec”库: https : //github.com/scodec/scodec
I've found that I've been using the following function a lot: 我发现我一直在使用以下功能:
/**
* 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)
This is useful if I have a case class where I don't want to use every value of the spec: 如果我有一个案例类,我不想使用规范的每个值,这很有用:
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]
This works well if the value I want to ignore isn't the last one in the hlist. 如果我想忽略的值不是hlist中的最后一个值,这很有效。 Would anyone know how to change the codec, if instead I wanted my case class to be: 有人知道如何更改编解码器,如果相反,我希望我的案例类是:
case class Example(value1: Int, value2: Int) // ignore value3 case类示例(value1:Int,value2:Int)//忽略value3
Any help is appreciated - thanks! 任何帮助表示赞赏 - 谢谢!
You can just use <~
, so instead of this: 你可以使用<~
,所以代替这个:
implicit val exampleCodec: Codec[Example] = (
("value1" | uint8) ::
("value2" | uint8).unit(0) :~>:
("value3" | uint8)
).as[Example]
You'd write this: 你写这个:
implicit val exampleCodec: Codec[Example] = (
("value1" | uint8) ::
("value3" | uint8) <~
("value2" | uint8).unit(0)
).as[Example]
Note that you explicitly have to make the codec a Codec[Unit]
—I'm using .unit(0)
here for the sake of example. 请注意,为了示例,您明确必须使编解码器成为Codec[Unit]
我在这里使用.unit .unit(0)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.