3

我刚开始使用 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) // 忽略 value3

任何帮助表示赞赏 - 谢谢!

4

1 回答 1

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)是为了举例。

于 2014-11-13T21:44:04.510 回答