且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Shapeless 提取字段名称?

更新时间:2023-02-18 22:48:14

可能是这样的,这个例子:

import shapeless._
import shapeless.ops.record._
import shapeless.ops.hlist.ToTraversable

trait FieldNames[T] {
  def apply(): List[String]
}

implicit def toNames[T, Repr <: HList, KeysRepr <: HList](
  implicit gen: LabelledGeneric.Aux[T, Repr],
  keys: Keys.Aux[Repr, KeysRepr],
  traversable: ToTraversable.Aux[KeysRepr, List, Symbol]
): FieldNames[T] = new FieldNames[T] {
  def apply() = keys().toList.map(_.name)
}

def fieldNames[T](implicit h : FieldNames[T]) = h()