Search code examples
scalagenericsshapeless

Extract FieldType key and value from HList


I would like to extract the key and value of the head of an HList using these two methods:

def getFieldName[K, V](value: FieldType[K, V])(implicit witness: Witness.Aux[K]): K = witness.value
def getFieldValue[K, V](value: FieldType[K, V]): V = value

I tried a few variations of this function, but I couldn't make it work, I think this might be the closest to the right solution:

def getFieldNameValue[Key <: Symbol, Value <: AnyRef, Y <: HList, A <: Product](a : A)
                       (implicit 
                        gen : LabelledGeneric.Aux[A, FieldType[Key, Value] :: Y],
                        witness: shapeless.Witness.Aux[Key]) = {
    val aGen = gen.to(a).head
    (getFieldName(aGen), getFieldValue(aGen))
  }

But it throws this exception:

could not find implicit value for parameter gen: shapeless.LabelledGeneric.Aux[Ex,shapeless.labelled.FieldType[Key,Value] :: Y]

I'd like to call it like this:

scala> case class Ex(i: Int, ii: Int)
scala> val ex = Ex(1,2)
scala> getFieldNameValue(ex)
res1: (String, Int) = (i,1)

Solution

  • This variant works:

      def getFieldNameValue[A <: Product, Repr <: HList,
                            K <: Symbol, V, T <: HList](a: A)(implicit 
        gen: LabelledGeneric.Aux[A, Repr],
        ev: Repr <:< (FieldType[K, V] :: T),
        witness: Witness.Aux[K]): (String, V) = {
        val record: Repr = gen.to(a)
        (witness.value.name, record.head)
      }
    
      getFieldNameValue(ex) // (i,1)
    

    I guess the trouble was that you tried to do too much work in one step (implicits don't like that).