Extract FieldType key and value from HList

ぐ巨炮叔叔 提交于 2021-02-05 08:12:56

问题


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)

回答1:


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).



来源:https://stackoverflow.com/questions/46259168/extract-fieldtype-key-and-value-from-hlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!