Scodec ignore last value when converting codecs between hlist and case class

I'm just starting out with the font-level "scodec" library: https://github.com/scodec/scodec

I found that I used 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 spec value:

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 is not the last one in the hlist. Does anyone know how to change the codec if instead I want my case class to be:

case class Example (value1: Int, value2: Int) // ignore value3

Any help is appreciated - thanks!

+3


source to share


1 answer


You can just use <~

, so instead:

implicit val exampleCodec: Codec[Example] = (
  ("value1" | uint8) :: 
  ("value2" | uint8).unit(0) :~>:
  ("value3" | uint8)
).as[Example]

      

You should 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 am using .unit(0)

here for example.

+3


source







All Articles