从HList中提取FieldType键和值 [英] Extract FieldType key and value from HList
本文介绍了从HList中提取FieldType键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用以下两种方法提取 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]
我想这样称呼它:
scala> case class Ex(i: Int, ii: Int)
scala> val ex = Ex(1,2)
scala> getFieldNameValue(ex)
res1: (String, Int) = (i,1)
推荐答案
此变体有效:
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).
这篇关于从HList中提取FieldType键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文