How to generically extract field names with Shapeless?

只谈情不闲聊 提交于 2020-07-04 13:44:08

问题


Given a case class A I can extract its field names with Shapeless using the following snippet:

val fieldNames: List[String] = {
  import shapeless._
  import shapeless.ops.record.Keys

  val gen = LabelledGeneric[A]
  val keys = Keys[gen.Repr].apply
  keys.toList.map(_.name)
}

This works all nice, but how can I implement this in a more generic manner, so that I can conveniently use this technique for arbitrary classes, like

val fields: List[String] = fieldNames[AnyCaseClass]

Is there a library that already does this for me?


回答1:


Something like this maybe, slightly modified version of this example:

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


来源:https://stackoverflow.com/questions/46525541/how-to-generically-extract-field-names-with-shapeless

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