kantan.csv icon indicating copy to clipboard operation
kantan.csv copied to clipboard

Custom CellCodec for Option

Open philippeehlert opened this issue 5 years ago • 1 comments

Hi! I'm trying to create a CellCodec that encodes/decodes Option[E] values in a way that:

  1. Option[E].empty values are encoded to - instead of an empty cell
  2. - values are decoded as Option[E].empty

Going through the source code, I imagined that it would be possible to do something using the already existent optionEncoder and optionDecoder, but I couldn't figure out how exactly to do it. Can you guys tell me if it is possible and give me any advice on how to do it?

Thanks!

philippeehlert avatar Sep 04 '19 17:09 philippeehlert

I'm so very sorry - I had answered this the day you posted it, but apparently I had no coverage and never realised my answer never actually got posted. I hope you managed to work it out on your own. Otherwise, I fear I might have lost a user, but here's a possible solution just in case somebody else needs it:

scala> implicit def opt[E: CellEncoder]: CellEncoder[Option[E]] = CellEncoder.from {
     |   case Some(e) => CellEncoder[E].encode(e)
     |   case None => "-"
     | }
opt: [E](implicit evidence$1: kantan.csv.CellEncoder[E])kantan.csv.CellEncoder[Option[E]]

scala> CellEncoder[Option[Int]].encode(Some(2))
res1: String = 2

scala> CellEncoder[Option[Int]].encode(None)
res2: String = -

nrinaudo avatar Jan 03 '20 21:01 nrinaudo