1

I would like to define a shapeless LabelledGeneric that ignores one (or more) fields when converting to HList; when converting the HList back again it should substitute a user-defined value. The goal is to be able to write something like this:

case class Foo(i: Int, s: String)
val foo = Foo(123, "Hello")

val gen = LabelledGeneric[Foo].ignoring('i)(defaultValue = -1)
val hlist = gen.to(foo)
// "Hello" :: HNil

val foo2 = gen.from(hlist)
assert(foo2 == Foo(-1, "Hello"))

This is what I have so far. It compiles, but I can't get the types to line up properly for implicit resolution when I try to use it:

implicit class IgnoringOps[T](orig: LabelledGeneric[T]) {
  def ignoring[Orig <: HList, V, Ign <: HList](k: Witness)(defaultValue: V)(implicit
   gen: LabelledGeneric.Aux[T, Orig],
   rem: Remover.Aux[Orig, FieldType[k.T, V], Ign],
   upd: Updater.Aux[Ign, FieldType[k.T, V], Orig]): LabelledGeneric[T] = {
    new LabelledGeneric[T] {
      override type Repr = Ign
      override def to(t: T): Ign = rem(gen.to(t))
      override def from(r: Ign): T = gen.from(upd(r, field[k.T](defaultValue)))
    }
  }
}

Can anyone shed any light on what I'm doing wrong?

Ashley Mercer
  • 2,058
  • 1
  • 16
  • 16

1 Answers1

2

This should work as intended (as per your example):

  implicit class IgnoringOps[T, L <: HList](gen: LabelledGeneric.Aux[T, L]) {
    def ignoring[V, I <: HList, H <: HList](k: Witness)(v: V)(implicit
      rem: Remover.Aux[L, k.T, (V, I)],
      upd: Updater.Aux[I, FieldType[k.T, V], H],
      ali: Align[H, L]
    ): LabelledGeneric[T] = new LabelledGeneric[T] {
      override type Repr = I

      //`rem` is implicitly used there
      override def to(t: T): I = gen.to(t) - k

      //`upd` and `ali` are implicitly used there
      override def from(r: I): T = gen.from(r + field[k.T](v))
    }
  }

Notes:

  • Removed implicit parameter gen: LabelledGeneric.Aux[T, L] from ignoring, you can leverage implicit class parameter orig;
  • Used - and + methods from RecordOps instead of using explicitly rem and upd;
  • Updated rem implicit parameter from Remover.Aux[L, FieldType[k.T, V], I], to Remover.Aux[L, k.T, (V, I)];
  • Added intermediate helper H <: HList;
  • Updated upd implicit parameter, using aforementioned intermediate helper, from Updater.Aux[I, FieldType[k.T, V], L] to Updater.Aux[I, FieldType[k.T, V], H];
  • Added ali implicitly asking for alignment of H and L: ali: Align[H, L]
Federico Pellegatta
  • 3,977
  • 1
  • 17
  • 29
  • Aha! I was missing the `Align` implicit, which I'd forgotten about (I tend to think of `record`s as unordered Maps, but of course the ordering matters when you're reconstructing the case class instance). Thank you :) – Ashley Mercer Apr 12 '17 at 17:30