jamborta jamborta -3 years ago 145
Scala Question

Shapeless HList appender

I'm trying to write a function that would append an

HList
, I found that
Updater
is the closest to what I want:

def appender[L <: HList, V, Out <: HList](hl: L, k: Witness, v: V)(implicit updater: Updater.Aux[L, FieldType[k.T, V], Out]) : Out = {
updater(hl, field[k.T](v))
}


I have this function that updates and appends an HList, but I'd like to disable the update and only allow the function to append, so that:

val hl = 'field1 ->> 1 :: HNil
appender(hl, 'field2, 2) //should compile
appender(hl, 'field1, 2) //should fail


Currently both compile. Anyway I can express this constraint with Shapeless? I thought maybe possible to ask evidence that the
Out
type is one element longer than the in type?

Answer Source

Use shapeless.ops.record.LacksKey:

  def appender[L <: HList, V, Out <: HList](hl: L, k: Witness, v: V)(implicit
                                                                     updater: Updater.Aux[L, FieldType[k.T, V], Out],
                                                                     lk: LacksKey[L, k.T]) : Out = {
    updater(hl, field[k.T](v))
  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download